Want to keep false positives to a minimum, even in "Messages".  The var message was coming up a lot when editing files where we wouldn't want to "fix" it, so I've silenced it.

There are a lot of "if statement can be simplified" messages in our files. I went through and fixed a bunch that came up when I was working on other things to validate the usefulness. It is the better choice at least 80% of the time, so I'm leaving it on.

Changes were primariliy made using the automated fixes. Flipped a few conditional blocks, again with the tooling.
This commit is contained in:
Jeremy Kuhne 2024-10-25 14:11:53 -07:00 коммит произвёл GitHub
Родитель f2afa04adf
Коммит 640825b4c9
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
20 изменённых файлов: 609 добавлений и 1645 удалений

Просмотреть файл

@ -407,6 +407,9 @@ dotnet_diagnostic.DOC107.severity = warning
# DOC108: Avoid empty paragraphs
dotnet_diagnostic.DOC108.severity = warning
# IDE0001: Simplify Names
dotnet_diagnostic.IDE0001.severity = warning
# IDE0002: Simplify Member Access
dotnet_diagnostic.IDE0002.severity = error
@ -418,6 +421,9 @@ dotnet_diagnostic.IDE0003.severity = error
# IDE0004: Remove unnecessary cast
dotnet_diagnostic.IDE0004.severity = silent
# IDE0008: Use explicit type instead of 'var'
dotnet_diagnostic.IDE0008.severity = silent
# IDE0017: Simplify object initialization
dotnet_diagnostic.IDE0017.severity = warning

Просмотреть файл

@ -79,10 +79,7 @@ public sealed unsafe partial class Graphics : MarshalByRefObject, IDisposable, I
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHdc(IntPtr hdc)
{
if (hdc == IntPtr.Zero)
throw new ArgumentNullException(nameof(hdc));
return FromHdcInternal(hdc);
return hdc == 0 ? throw new ArgumentNullException(nameof(hdc)) : FromHdcInternal(hdc);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]

Просмотреть файл

@ -53,9 +53,7 @@ public abstract unsafe class Image : MarshalByRefObject, IImage, IDisposable, IC
private protected Image() { }
#pragma warning disable CA2229 // Implement serialization constructors
private protected Image(SerializationInfo info, StreamingContext context)
#pragma warning restore CA2229
{
byte[] dat = (byte[])info.GetValue("Data", typeof(byte[]))!; // Do not rename (binary serialization)

Просмотреть файл

@ -1089,7 +1089,7 @@ public class GraphicsPathTests
gp.AddRectangle(new Rectangle(1, 1, 2, 2));
AssertRectangle(gp);
gp.Transform(matrix);
Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements);
Assert.Equal([1f, 1f, 2f, 2f, 3f, 3f], matrix.Elements);
Assert.Equal(new RectangleF(6f, 6f, 6f, 6f), gp.GetBounds());
Assert.Equal([new(6f, 6f), new(8f, 8f), new(12f, 12f), new(10f, 10f)], gp.PathPoints);
Assert.Equal(new byte[] { 0, 1, 1, 129 }, gp.PathTypes);
@ -1101,7 +1101,7 @@ public class GraphicsPathTests
using GraphicsPath gp = new();
using Matrix matrix = new(1f, 1f, 2f, 2f, 3f, 3f);
gp.Transform(matrix);
Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements);
Assert.Equal([1f, 1f, 2f, 2f, 3f, 3f], matrix.Elements);
AssertEmptyGraphicsPath(gp);
}

Просмотреть файл

@ -13,7 +13,7 @@ public partial class MatrixTests
{
Matrix3x2 matrix3X2 = new(m11, m12, m21, m22, dx, dy);
using Matrix matrix = new(matrix3X2);
Assert.Equal(new float[] { m11, m12, m21, m22, dx, dy }, matrix.Elements);
Assert.Equal([m11, m12, m21, m22, dx, dy], matrix.Elements);
Assert.Equal(matrix3X2, matrix.MatrixElements);
Assert.Equal(isIdentity, matrix.IsIdentity);
Assert.Equal(isInvertible, matrix.IsInvertible);
@ -28,7 +28,7 @@ public partial class MatrixTests
Matrix3x2 matrix3X2 = new(m11, m12, m21, m22, dx, dy);
using Matrix matrix = new();
matrix.MatrixElements = matrix3X2;
Assert.Equal(new float[] { m11, m12, m21, m22, dx, dy }, matrix.Elements);
Assert.Equal([m11, m12, m21, m22, dx, dy], matrix.Elements);
Assert.Equal(matrix3X2, matrix.MatrixElements);
Assert.Equal(isIdentity, matrix.IsIdentity);
Assert.Equal(isInvertible, matrix.IsInvertible);

Просмотреть файл

@ -66,7 +66,7 @@ public partial class MatrixTests
public void Ctor_Elements(float m11, float m12, float m21, float m22, float dx, float dy, bool isIdentity, bool isInvertible)
{
using Matrix matrix = new(m11, m12, m21, m22, dx, dy);
Assert.Equal(new float[] { m11, m12, m21, m22, dx, dy }, matrix.Elements);
Assert.Equal([m11, m12, m21, m22, dx, dy], matrix.Elements);
Assert.Equal(isIdentity, matrix.IsIdentity);
Assert.Equal(isInvertible, matrix.IsInvertible);
Assert.Equal(dx, matrix.OffsetX);

Просмотреть файл

@ -451,18 +451,18 @@ public class PathGradientBrushTests
Assert.True(brush.Transform.IsIdentity);
if (focus == 0f)
{
Assert.Equal(new float[2] { defaultScale, 0f }, brush.Blend.Factors);
Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions);
Assert.Equal([defaultScale, 0f], brush.Blend.Factors);
Assert.Equal([focus, 1f], brush.Blend.Positions);
}
else if (focus == 1f)
{
Assert.Equal(new float[2] { 0f, defaultScale }, brush.Blend.Factors);
Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions);
Assert.Equal([0f, defaultScale], brush.Blend.Factors);
Assert.Equal([0f, focus], brush.Blend.Positions);
}
else
{
Assert.Equal(new float[3] { 0f, defaultScale, 0f }, brush.Blend.Factors);
Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions);
Assert.Equal([0f, defaultScale, 0f], brush.Blend.Factors);
Assert.Equal([0f, focus, 1f], brush.Blend.Positions);
}
}
@ -478,18 +478,18 @@ public class PathGradientBrushTests
Assert.True(brush.Transform.IsIdentity);
if (focus == 0f)
{
Assert.Equal(new float[2] { 1f, 0f }, brush.Blend.Factors);
Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions);
Assert.Equal([1f, 0f], brush.Blend.Factors);
Assert.Equal([focus, 1f], brush.Blend.Positions);
}
else if (focus == 1f)
{
Assert.Equal(new float[2] { 0f, 1f }, brush.Blend.Factors);
Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions);
Assert.Equal([0f, 1f], brush.Blend.Factors);
Assert.Equal([0f, focus], brush.Blend.Positions);
}
else
{
Assert.Equal(new float[3] { 0f, 1f, 0f }, brush.Blend.Factors);
Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions);
Assert.Equal([0f, 1f, 0f], brush.Blend.Factors);
Assert.Equal([0f, focus, 1f], brush.Blend.Positions);
}
}

Просмотреть файл

@ -21,7 +21,7 @@ public class ImageTests
public void PropertyIdList_GetBitmapJpg_Success()
{
using Bitmap bitmap = new(Helpers.GetTestBitmapPath("nature24bits.jpg"));
Assert.Equal(new int[] { PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable], bitmap.PropertyIdList);
Assert.NotSame(bitmap.PropertyIdList, bitmap.PropertyIdList);
}
@ -135,12 +135,12 @@ public class ImageTests
bitmap.SetPropertyItem(item3);
bitmap.RemovePropertyItem(PropertyTagExifUserComment);
Assert.Equal(new int[] { PropertyTagChrominanceTable, PropertyTagLuminanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagChrominanceTable, PropertyTagLuminanceTable], bitmap.PropertyIdList);
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.GetPropertyItem(PropertyTagExifUserComment));
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.RemovePropertyItem(PropertyTagExifUserComment));
bitmap.RemovePropertyItem(PropertyTagLuminanceTable);
Assert.Equal(new int[] { PropertyTagChrominanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagChrominanceTable], bitmap.PropertyIdList);
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.GetPropertyItem(PropertyTagLuminanceTable));
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.RemovePropertyItem(PropertyTagLuminanceTable));
@ -155,12 +155,12 @@ public class ImageTests
{
using Bitmap bitmap = new(Helpers.GetTestBitmapPath("nature24bits.jpg"));
bitmap.RemovePropertyItem(PropertyTagExifUserComment);
Assert.Equal(new int[] { PropertyTagChrominanceTable, PropertyTagLuminanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagChrominanceTable, PropertyTagLuminanceTable], bitmap.PropertyIdList);
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.GetPropertyItem(PropertyTagExifUserComment));
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.RemovePropertyItem(PropertyTagExifUserComment));
bitmap.RemovePropertyItem(PropertyTagLuminanceTable);
Assert.Equal(new int[] { PropertyTagChrominanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagChrominanceTable], bitmap.PropertyIdList);
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.GetPropertyItem(PropertyTagLuminanceTable));
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.RemovePropertyItem(PropertyTagLuminanceTable));
@ -234,7 +234,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment], bitmap.PropertyIdList);
PropertyItem[] items = bitmap.PropertyItems;
Assert.Single(items);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -249,7 +249,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(2, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -264,7 +264,7 @@ public class ImageTests
// Set same.
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(2, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -292,7 +292,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable], bitmap.PropertyIdList);
PropertyItem[] items = bitmap.PropertyItems;
Assert.Equal(3, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -335,7 +335,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(4, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -378,7 +378,7 @@ public class ImageTests
// Set same.
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, PropertyTagChrominanceTable, PropertyTagLuminanceTable, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(4, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -435,7 +435,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment], bitmap.PropertyIdList);
PropertyItem[] items = bitmap.PropertyItems;
Assert.Single(items);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -450,7 +450,7 @@ public class ImageTests
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(2, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -465,7 +465,7 @@ public class ImageTests
// Set same.
bitmap.SetPropertyItem(item);
Assert.Equal(new int[] { PropertyTagExifUserComment, propid }, bitmap.PropertyIdList);
Assert.Equal([PropertyTagExifUserComment, propid], bitmap.PropertyIdList);
items = bitmap.PropertyItems;
Assert.Equal(2, items.Length);
Assert.Equal(PropertyTagExifUserComment, items[0].Id);
@ -660,7 +660,7 @@ public class ImageTests
public void Save_InvalidDirectory_ThrowsDirectoryNotFoundException()
{
using Bitmap bitmap = new(1, 1);
string badTarget = System.IO.Path.Combine("NoSuchDirectory", "NoSuchFile");
string badTarget = Path.Join("NoSuchDirectory", "NoSuchFile");
AssertExtensions.Throws<DirectoryNotFoundException>(() => bitmap.Save(badTarget), $"The directory NoSuchDirectory of the filename {badTarget} does not exist.");
}
}

Просмотреть файл

@ -1307,7 +1307,7 @@ public partial class ControlDesigner : ComponentDesigner
_ctrlSelect = (Control.ModifierKeys & Keys.Control) != 0;
// If the CTRL key isn't down, select this component, otherwise, we wait until the mouse up. Make sure the component is selected
if (!_ctrlSelect && TryGetService<ISelectionService>(out ISelectionService? selectionService))
if (!_ctrlSelect && TryGetService(out ISelectionService? selectionService))
{
selectionService.SetSelectedComponents(new object[] { Component }, SelectionTypes.Primary);
}
@ -1398,7 +1398,7 @@ public partial class ControlDesigner : ComponentDesigner
// Make sure the component is selected
// But only select it if it is not already the primary selection, and we want to toggle the current primary selection.
if (TryGetService<ISelectionService>(out ISelectionService? selectionService) && !Component.Equals(selectionService.PrimarySelection))
if (TryGetService(out ISelectionService? selectionService) && !Component.Equals(selectionService.PrimarySelection))
{
selectionService.SetSelectedComponents(new object[] { Component }, SelectionTypes.Primary | SelectionTypes.Toggle);
}
@ -1845,14 +1845,9 @@ public partial class ControlDesigner : ComponentDesigner
case PInvokeCore.WM_LBUTTONDBLCLK:
case PInvokeCore.WM_NCRBUTTONDBLCLK:
case PInvokeCore.WM_RBUTTONDBLCLK:
if (m.MsgInternal == PInvokeCore.WM_NCRBUTTONDBLCLK || m.MsgInternal == PInvokeCore.WM_RBUTTONDBLCLK)
{
button = MouseButtons.Right;
}
else
{
button = MouseButtons.Left;
}
button = m.MsgInternal == PInvokeCore.WM_NCRBUTTONDBLCLK || m.MsgInternal == PInvokeCore.WM_RBUTTONDBLCLK
? MouseButtons.Right
: MouseButtons.Left;
if (button == MouseButtons.Left)
{
@ -1873,14 +1868,9 @@ public partial class ControlDesigner : ComponentDesigner
case PInvokeCore.WM_LBUTTONDOWN:
case PInvokeCore.WM_NCRBUTTONDOWN:
case PInvokeCore.WM_RBUTTONDOWN:
if (m.MsgInternal == PInvokeCore.WM_NCRBUTTONDOWN || m.MsgInternal == PInvokeCore.WM_RBUTTONDOWN)
{
button = MouseButtons.Right;
}
else
{
button = MouseButtons.Left;
}
button = m.MsgInternal == PInvokeCore.WM_NCRBUTTONDOWN || m.MsgInternal == PInvokeCore.WM_RBUTTONDOWN
? MouseButtons.Right
: MouseButtons.Left;
// We don't really want the focus, but we want to focus the designer. Below we handle WM_SETFOCUS
// and do the right thing.
@ -2314,36 +2304,30 @@ public partial class ControlDesigner : ComponentDesigner
private IOverlayService? OverlayService => _overlayService ??= GetService<IOverlayService>();
private static bool IsMouseMessage(MessageId msg)
{
if (msg >= PInvokeCore.WM_MOUSEFIRST && msg <= PInvokeCore.WM_MOUSELAST)
{
return true;
}
return (uint)msg switch
{
// WM messages not covered by the above block
PInvokeCore.WM_MOUSEHOVER
or PInvokeCore.WM_MOUSELEAVE
or PInvokeCore.WM_NCMOUSEMOVE
or PInvokeCore.WM_NCLBUTTONDOWN
or PInvokeCore.WM_NCLBUTTONUP
or PInvokeCore.WM_NCLBUTTONDBLCLK
or PInvokeCore.WM_NCRBUTTONDOWN
or PInvokeCore.WM_NCRBUTTONUP
or PInvokeCore.WM_NCRBUTTONDBLCLK
or PInvokeCore.WM_NCMBUTTONDOWN
or PInvokeCore.WM_NCMBUTTONUP
or PInvokeCore.WM_NCMBUTTONDBLCLK
or PInvokeCore.WM_NCMOUSEHOVER
or PInvokeCore.WM_NCMOUSELEAVE
or PInvokeCore.WM_NCXBUTTONDOWN
or PInvokeCore.WM_NCXBUTTONUP
or PInvokeCore.WM_NCXBUTTONDBLCLK => true,
_ => false,
};
}
private static bool IsMouseMessage(MessageId msg) =>
(msg >= PInvokeCore.WM_MOUSEFIRST && msg <= PInvokeCore.WM_MOUSELAST)
|| (uint)msg switch
{
// WM messages not covered by the above block
PInvokeCore.WM_MOUSEHOVER
or PInvokeCore.WM_MOUSELEAVE
or PInvokeCore.WM_NCMOUSEMOVE
or PInvokeCore.WM_NCLBUTTONDOWN
or PInvokeCore.WM_NCLBUTTONUP
or PInvokeCore.WM_NCLBUTTONDBLCLK
or PInvokeCore.WM_NCRBUTTONDOWN
or PInvokeCore.WM_NCRBUTTONUP
or PInvokeCore.WM_NCRBUTTONDBLCLK
or PInvokeCore.WM_NCMBUTTONDOWN
or PInvokeCore.WM_NCMBUTTONUP
or PInvokeCore.WM_NCMBUTTONDBLCLK
or PInvokeCore.WM_NCMOUSEHOVER
or PInvokeCore.WM_NCMOUSELEAVE
or PInvokeCore.WM_NCXBUTTONDOWN
or PInvokeCore.WM_NCXBUTTONUP
or PInvokeCore.WM_NCXBUTTONDBLCLK => true,
_ => false,
};
private bool IsDoubleClick(int x, int y)
{

Просмотреть файл

@ -374,12 +374,9 @@ internal static class DesignerUtils
return prop?.GetValue(null);
}
if (provider.TryGetService(out IDesignerOptionService? optionService))
{
return optionService.GetOptionValue("WindowsFormsDesigner\\General", name);
}
return null;
return provider.TryGetService(out IDesignerOptionService? optionService)
? optionService.GetOptionValue("WindowsFormsDesigner\\General", name)
: null;
}
/// <summary>
@ -452,12 +449,7 @@ internal static class DesignerUtils
}
// Now check to see if our center pixel was cleared, if not then our WM_PRINT failed
if (image.GetPixel(image.Width / 2, image.Height / 2).Equals(testColor))
{
return false;
}
return true;
return !image.GetPixel(image.Width / 2, image.Height / 2).Equals(testColor);
}
/// <summary>
@ -730,17 +722,8 @@ internal static class DesignerUtils
/// Ensures that a SplitterPanel in a SplitContainer returns the same container as other form components,
/// since SplitContainer sites its two SplitterPanels inside a nested container.
/// </summary>
public static IContainer? CheckForNestedContainer(IContainer? container)
{
if (container is NestedContainer nestedContainer)
{
return nestedContainer.Owner.Site?.Container;
}
else
{
return container;
}
}
public static IContainer? CheckForNestedContainer(IContainer? container) =>
container is NestedContainer nestedContainer ? (nestedContainer.Owner.Site?.Container) : container;
/// <summary>
/// Used to create copies of the objects that we are dragging in a drag operation

Просмотреть файл

@ -965,15 +965,7 @@ internal partial class OleDragDropHandler
Point convertedPoint = Destination.GetDesignerControl().PointToClient(new Point(de.X, de.Y));
// draw the shadow rectangles.
Point newOffset;
if (_forceDrawFrames)
{
newOffset = convertedPoint;
}
else
{
newOffset = new Point(de.X - _dragBase.X, de.Y - _dragBase.Y);
}
Point newOffset = _forceDrawFrames ? convertedPoint : new Point(de.X - _dragBase.X, de.Y - _dragBase.Y);
// Only allow drops on the client area.
if (!Destination.GetDesignerControl().ClientRectangle.Contains(convertedPoint))
@ -1035,28 +1027,16 @@ internal partial class OleDragDropHandler
components = cdo.Components;
}
if (!topLevelOnly || components is null)
{
return components;
}
return GetTopLevelComponents(components);
return !topLevelOnly || components is null ? components : GetTopLevelComponents(components);
}
public static object[]? GetDraggingObjects(IDataObject? dataObj)
{
return GetDraggingObjects(dataObj, false);
}
public static object[]? GetDraggingObjects(IDataObject? dataObj) => GetDraggingObjects(dataObj, topLevelOnly: false);
public static object[]? GetDraggingObjects(DragEventArgs de)
{
return GetDraggingObjects(de.Data);
}
public static object[]? GetDraggingObjects(DragEventArgs de) => GetDraggingObjects(de.Data);
private static object[] GetTopLevelComponents(ICollection comps)
{
// Filter the top-level components.
//
if (comps is not IList)
{
comps = new ArrayList(comps);

Просмотреть файл

@ -1472,17 +1472,9 @@ public unsafe partial class Control :
// We only do ambients for things with "Cursors.Default" as their default.
Cursor localDefault = DefaultCursor;
if (localDefault != Cursors.Default)
{
return localDefault;
}
if (ParentInternal is { } parent)
{
return parent.Cursor;
}
return AmbientPropertiesService?.Cursor ?? localDefault;
return localDefault != Cursors.Default
? localDefault
: ParentInternal is { } parent ? parent.Cursor : AmbientPropertiesService?.Cursor ?? localDefault;
}
set
{
@ -2799,15 +2791,9 @@ public unsafe partial class Control :
/// </summary>
internal BoundsSpecified RequiredScaling
{
get
{
if ((_requiredScaling & RequiredScalingEnabledMask) != 0)
{
return (BoundsSpecified)(_requiredScaling & RequiredScalingMask);
}
return BoundsSpecified.None;
}
get => (_requiredScaling & RequiredScalingEnabledMask) != 0
? (BoundsSpecified)(_requiredScaling & RequiredScalingMask)
: BoundsSpecified.None;
set
{
byte enableBit = (byte)(_requiredScaling & RequiredScalingEnabledMask);
@ -4337,20 +4323,8 @@ public unsafe partial class Control :
/// all controls in the parent chain can do it too, but since the semantics for this function can be overridden,
/// we need to call the method on the parent 'recursively' (not exactly since it is not necessarily the same method).
/// </summary>
internal virtual bool CanProcessMnemonic()
{
if (!Enabled || !Visible)
{
return false;
}
if (_parent is not null)
{
return _parent.CanProcessMnemonic();
}
return true;
}
internal virtual bool CanProcessMnemonic() =>
Enabled && Visible && (_parent is null || _parent.CanProcessMnemonic());
// Package scope to allow AxHost to override
internal virtual bool CanSelectCore()
@ -4955,18 +4929,10 @@ public unsafe partial class Control :
}
Debug.Assert(asyncResult.IsCompleted, "Why isn't this asyncResult done yet?");
if (entry._exception is not null)
{
throw entry._exception;
}
return entry._retVal;
return entry._exception is not null ? throw entry._exception : entry._retVal;
}
internal bool EndUpdateInternal()
{
return EndUpdateInternal(true);
}
internal bool EndUpdateInternal() => EndUpdateInternal(invalidate: true);
internal bool EndUpdateInternal(bool invalidate)
{
@ -5654,15 +5620,10 @@ public unsafe partial class Control :
}
else
{
// If we don't found any siblings, and the control is a ToolStripItem that hosts a control itself,
// If we haven't found any siblings, and the control is a ToolStripItem that hosts a control itself,
// then we shouldn't return its parent, because it would be the same ToolStrip we're currently at.
// Instead, we should return the control that is previous to the current ToolStrip
if (ctl.ToolStripControlHost is not null)
{
return GetNextControl(ctl._parent, forward: false);
}
return parent;
// Instead, we should return the control that is previous to the current ToolStrip.
return ctl.ToolStripControlHost is not null ? GetNextControl(ctl._parent, forward: false) : parent;
}
}
}
@ -5702,14 +5663,9 @@ public unsafe partial class Control :
else
{
HWND hwnd = (HWND)window.Handle;
if (hwnd.IsNull || PInvoke.IsWindow(hwnd))
{
return new(window, hwnd);
}
else
{
throw new Win32Exception((int)WIN32_ERROR.ERROR_INVALID_HANDLE);
}
return hwnd.IsNull || PInvoke.IsWindow(hwnd)
? new(window, hwnd)
: throw new Win32Exception((int)WIN32_ERROR.ERROR_INVALID_HANDLE);
}
}
@ -6160,14 +6116,7 @@ public unsafe partial class Control :
{
lock (_threadCallbackList)
{
if (_threadCallbackList.Count > 0)
{
current = _threadCallbackList.Dequeue();
}
else
{
current = null;
}
current = _threadCallbackList.Count > 0 ? _threadCallbackList.Dequeue() : null;
}
}
}
@ -6223,12 +6172,7 @@ public unsafe partial class Control :
// and off when the key is untoggled.
// Toggle keys (only low bit is of interest).
if (keyVal is Keys.Insert or Keys.CapsLock)
{
return (result & 0x1) != 0x0;
}
return (result & 0x8001) != 0x0;
return keyVal is Keys.Insert or Keys.CapsLock ? (result & 0x1) != 0x0 : (result & 0x8001) != 0x0;
}
// else - it's an un-lockable key.
@ -8889,14 +8833,7 @@ public unsafe partial class Control :
OnKeyPress(kpe);
// If the character wasn't changed, just use the original value rather than round tripping.
if (kpe.KeyChar == preEventCharacter)
{
newWParam = m.WParamInternal;
}
else
{
newWParam = (WPARAM)kpe.KeyChar;
}
newWParam = kpe.KeyChar == preEventCharacter ? m.WParamInternal : (WPARAM)kpe.KeyChar;
}
else
{
@ -8942,15 +8879,8 @@ public unsafe partial class Control :
/// <see cref="Message.Msg"/> property are WM_CHAR, WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, and WM_SYSKEYUP.
/// </para>
/// </remarks>
protected internal virtual bool ProcessKeyMessage(ref Message m)
{
if (_parent is not null && _parent.ProcessKeyPreview(ref m))
{
return true;
}
return ProcessKeyEventArgs(ref m);
}
protected internal virtual bool ProcessKeyMessage(ref Message m) =>
(_parent is not null && _parent.ProcessKeyPreview(ref m)) || ProcessKeyEventArgs(ref m);
/// <summary>
/// Previews a keyboard message.
@ -11226,20 +11156,7 @@ public unsafe partial class Control :
/// </summary>
private void WmGetControlName(ref Message m)
{
string? name;
if (Site is not null)
{
name = Site.Name;
}
else
{
name = Name;
}
name ??= string.Empty;
MarshalStringToMessage(name, ref m);
MarshalStringToMessage(Site?.Name ?? Name ?? string.Empty, ref m);
}
/// <summary>

Просмотреть файл

@ -255,17 +255,7 @@ public partial class ComboBox : ListControl
/// </summary>
public override Color BackColor
{
get
{
if (ShouldSerializeBackColor())
{
return base.BackColor;
}
else
{
return SystemColors.Window;
}
}
get => ShouldSerializeBackColor() ? base.BackColor : SystemColors.Window;
set => base.BackColor = value;
}
@ -488,15 +478,7 @@ public partial class ComboBox : ListControl
[SRDescription(nameof(SR.ComboBoxDroppedDownDescr))]
public bool DroppedDown
{
get
{
if (IsHandleCreated)
{
return (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETDROPPEDSTATE) != 0;
}
return false;
}
get => IsHandleCreated && (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETDROPPEDSTATE) != 0;
set
{
if (!IsHandleCreated)
@ -553,17 +535,7 @@ public partial class ComboBox : ListControl
/// </summary>
public override Color ForeColor
{
get
{
if (ShouldSerializeForeColor())
{
return base.ForeColor;
}
else
{
return SystemColors.WindowText;
}
}
get => ShouldSerializeForeColor() ? base.ForeColor : SystemColors.WindowText;
set => base.ForeColor = value;
}
@ -579,10 +551,7 @@ public partial class ComboBox : ListControl
[SRDescription(nameof(SR.ComboBoxIntegralHeightDescr))]
public bool IntegralHeight
{
get
{
return _integralHeight;
}
get => _integralHeight;
set
{
if (_integralHeight != value)
@ -619,12 +588,7 @@ public partial class ComboBox : ListControl
Debug.Assert(IsHandleCreated, "Handle should be created at this point");
int height = (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETITEMHEIGHT);
if (height == -1)
{
throw new Win32Exception();
}
return height;
return height == -1 ? throw new Win32Exception() : height;
}
set
{
@ -899,15 +863,7 @@ public partial class ComboBox : ListControl
[SRDescription(nameof(SR.ComboBoxSelectedIndexDescr))]
public override int SelectedIndex
{
get
{
if (IsHandleCreated)
{
return (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETCURSEL);
}
return _selectedIndex;
}
get => IsHandleCreated ? (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETCURSEL) : _selectedIndex;
set
{
if (SelectedIndex == value)
@ -988,15 +944,7 @@ public partial class ComboBox : ListControl
[SRDescription(nameof(SR.ComboBoxSelectedTextDescr))]
public string SelectedText
{
get
{
if (DropDownStyle == ComboBoxStyle.DropDownList)
{
return string.Empty;
}
return Text.Substring(SelectionStart, SelectionLength);
}
get => DropDownStyle == ComboBoxStyle.DropDownList ? string.Empty : Text.Substring(SelectionStart, SelectionLength);
set
{
if (DropDownStyle != ComboBoxStyle.DropDownList)
@ -2015,12 +1963,7 @@ public partial class ComboBox : ListControl
if (IsHandleCreated)
{
int h = (int)PInvokeCore.SendMessage(this, PInvoke.CB_GETITEMHEIGHT, (WPARAM)index);
if (h == -1)
{
throw new Win32Exception();
}
return h;
return h == -1 ? throw new Win32Exception() : h;
}
return ItemHeight;
@ -2213,12 +2156,7 @@ public partial class ComboBox : ListControl
{
Debug.Assert(IsHandleCreated, "Shouldn't be calling Native methods before the handle is created.");
int insertIndex = (int)PInvokeCore.SendMessage(this, PInvoke.CB_ADDSTRING, (WPARAM)0, GetItemText(item));
if (insertIndex < 0)
{
throw new OutOfMemoryException(SR.ComboBoxItemOverflow);
}
return insertIndex;
return insertIndex < 0 ? throw new OutOfMemoryException(SR.ComboBoxItemOverflow) : insertIndex;
}
/// <summary>
@ -3020,25 +2958,13 @@ public partial class ComboBox : ListControl
return returnedValue;
}
protected override bool ProcessKeyEventArgs(ref Message m)
{
if (AutoCompleteMode != AutoCompleteMode.None
&& AutoCompleteSource == AutoCompleteSource.ListItems
&& DropDownStyle == ComboBoxStyle.DropDownList
&& InterceptAutoCompleteKeystroke(m))
{
return true;
}
else
{
return base.ProcessKeyEventArgs(ref m);
}
}
protected override bool ProcessKeyEventArgs(ref Message m) => (AutoCompleteMode != AutoCompleteMode.None
&& AutoCompleteSource == AutoCompleteSource.ListItems
&& DropDownStyle == ComboBoxStyle.DropDownList
&& InterceptAutoCompleteKeystroke(m))
|| base.ProcessKeyEventArgs(ref m);
private void ResetHeightCache()
{
_prefHeightCache = -1;
}
private void ResetHeightCache() => _prefHeightCache = -1;
/// <summary>
/// Reparses the objects, getting new text strings for them.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -351,12 +351,7 @@ public sealed partial class ImageList : Component, IHandle<HIMAGELIST>
{
Debug.Assert(HandleCreated, "Calling AddIconToHandle when there is no handle");
int index = PInvoke.ImageList.ReplaceIcon(this, -1, new HandleRef<HICON>(icon, (HICON)icon.Handle));
if (index == -1)
{
throw new InvalidOperationException(SR.ImageListAddFailed);
}
return index;
return index == -1 ? throw new InvalidOperationException(SR.ImageListAddFailed) : index;
}
finally
{
@ -392,12 +387,7 @@ public sealed partial class ImageList : Component, IHandle<HIMAGELIST>
PInvokeCore.DeleteObject(hMask);
}
if (index == -1)
{
throw new InvalidOperationException(SR.ImageListAddFailed);
}
return index;
return index == -1 ? throw new InvalidOperationException(SR.ImageListAddFailed) : index;
}
/// <summary>

Просмотреть файл

@ -77,20 +77,15 @@ public partial class ListView
return element ?? base.ElementProviderFromPoint(x, y);
}
internal override IRawElementProviderFragment.Interface? FragmentNavigate(NavigateDirection direction)
{
if (!this.IsOwnerHandleCreated(out ListView? _))
{
return null;
}
return direction switch
{
NavigateDirection.NavigateDirection_FirstChild => GetChild(0),
NavigateDirection.NavigateDirection_LastChild => GetLastChild(),
_ => base.FragmentNavigate(direction)
};
}
internal override IRawElementProviderFragment.Interface? FragmentNavigate(NavigateDirection direction) =>
!this.IsOwnerHandleCreated(out ListView? _)
? null
: direction switch
{
NavigateDirection.NavigateDirection_FirstChild => GetChild(0),
NavigateDirection.NavigateDirection_LastChild => GetLastChild(),
_ => base.FragmentNavigate(direction)
};
public override AccessibleObject? GetChild(int index)
{
@ -155,30 +150,18 @@ public partial class ListView
return InvalidIndex;
}
internal override int GetChildIndex(AccessibleObject? child)
{
if (!this.TryGetOwnerAs(out ListView? owningListView))
{
return base.GetChildIndex(child);
}
internal override int GetChildIndex(AccessibleObject? child) => this.TryGetOwnerAs(out ListView? owningListView)
? owningListView.GroupsDisplayed ? GetGroupIndex(child) : GetItemIndex(child)
: base.GetChildIndex(child);
return owningListView.GroupsDisplayed ? GetGroupIndex(child) : GetItemIndex(child);
}
private string GetItemStatus()
{
if (!this.TryGetOwnerAs(out ListView? owningListView))
{
return string.Empty;
}
return owningListView.Sorting switch
private string GetItemStatus() => this.TryGetOwnerAs(out ListView? owningListView)
? owningListView.Sorting switch
{
SortOrder.Ascending => SR.SortedAscendingAccessibleStatus,
SortOrder.Descending => SR.SortedDescendingAccessibleStatus,
_ => SR.NotSortedAccessibleStatus
};
}
}
: string.Empty;
internal override IRawElementProviderSimple.Interface[]? GetColumnHeaders()
{
@ -361,23 +344,13 @@ public partial class ListView
return null;
}
internal override bool IsPatternSupported(UIA_PATTERN_ID patternId)
{
if (!this.TryGetOwnerAs(out ListView? owningListView))
{
return false;
}
if (patternId == UIA_PATTERN_ID.UIA_SelectionPatternId ||
patternId == UIA_PATTERN_ID.UIA_MultipleViewPatternId ||
(patternId == UIA_PATTERN_ID.UIA_GridPatternId && owningListView.View == View.Details) ||
(patternId == UIA_PATTERN_ID.UIA_TablePatternId && owningListView.View == View.Details))
{
return true;
}
return base.IsPatternSupported(patternId);
}
internal override bool IsPatternSupported(UIA_PATTERN_ID patternId) =>
this.TryGetOwnerAs(out ListView? owningListView)
&& (patternId == UIA_PATTERN_ID.UIA_SelectionPatternId
|| patternId == UIA_PATTERN_ID.UIA_MultipleViewPatternId
|| (patternId == UIA_PATTERN_ID.UIA_GridPatternId && owningListView.View == View.Details)
|| (patternId == UIA_PATTERN_ID.UIA_TablePatternId && owningListView.View == View.Details)
|| base.IsPatternSupported(patternId));
internal override void SetMultiViewProviderCurrentView(int viewId)
{

Просмотреть файл

@ -345,17 +345,7 @@ public partial class ListView : Control
public override Color BackColor
{
get
{
if (ShouldSerializeBackColor())
{
return base.BackColor;
}
else
{
return SystemColors.Window;
}
}
get => ShouldSerializeBackColor() ? base.BackColor : SystemColors.Window;
set
{
base.BackColor = value;
@ -403,14 +393,9 @@ public partial class ListView : Control
fixed (char* pBackgroundImageFileName = _backgroundImageFileName)
{
LVBKIMAGEW lvbkImage = default;
if (BackgroundImageTiled)
{
lvbkImage.ulFlags = LIST_VIEW_BACKGROUND_IMAGE_FLAGS.LVBKIF_STYLE_TILE;
}
else
{
lvbkImage.ulFlags = LIST_VIEW_BACKGROUND_IMAGE_FLAGS.LVBKIF_STYLE_NORMAL;
}
lvbkImage.ulFlags = BackgroundImageTiled
? LIST_VIEW_BACKGROUND_IMAGE_FLAGS.LVBKIF_STYLE_TILE
: LIST_VIEW_BACKGROUND_IMAGE_FLAGS.LVBKIF_STYLE_NORMAL;
lvbkImage.ulFlags |= LIST_VIEW_BACKGROUND_IMAGE_FLAGS.LVBKIF_SOURCE_URL;
lvbkImage.pszImage = pBackgroundImageFileName;
@ -845,17 +830,7 @@ public partial class ListView : Control
public override Color ForeColor
{
get
{
if (ShouldSerializeForeColor())
{
return base.ForeColor;
}
else
{
return SystemColors.WindowText;
}
}
get => ShouldSerializeForeColor() ? base.ForeColor : SystemColors.WindowText;
set
{
base.ForeColor = value;
@ -1741,23 +1716,11 @@ public partial class ListView : Control
if (!IsHandleCreated)
{
if (Items.Count > 0)
{
return Items[0];
}
else
{
return null;
}
return Items.Count > 0 ? Items[0] : null;
}
_topIndex = (int)PInvokeCore.SendMessage(this, PInvoke.LVM_GETTOPINDEX);
if (_topIndex >= 0 && _topIndex < Items.Count)
{
return Items[_topIndex];
}
return null;
return _topIndex >= 0 && _topIndex < Items.Count ? Items[_topIndex] : null;
}
set
{
@ -2872,14 +2835,9 @@ public partial class ListView : Control
if (changeColor)
{
if (!haveRenderInfo || riFore.IsEmpty)
{
nmcd->clrText = ColorTranslator.ToWin32(_odCacheForeColor);
}
else
{
nmcd->clrText = ColorTranslator.ToWin32(riFore);
}
nmcd->clrText = !haveRenderInfo || riFore.IsEmpty
? (COLORREF)ColorTranslator.ToWin32(_odCacheForeColor)
: (COLORREF)ColorTranslator.ToWin32(riFore);
// Work-around for a comctl quirk where,
// if clrText is the same as SystemColors.HotTrack,
@ -2902,14 +2860,7 @@ public partial class ListView : Control
{
int n = 16 - totalshift;
// Make sure the value doesn't overflow
if (color == mask)
{
color = ((color >> n) - 1) << n;
}
else
{
color = ((color >> n) + 1) << n;
}
color = color == mask ? ((color >> n) - 1) << n : ((color >> n) + 1) << n;
// Copy the adjustment into nmcd->clrText
nmcd->clrText = (COLORREF)((int)(nmcd->clrText & (~mask)) | color);
@ -2927,14 +2878,9 @@ public partial class ListView : Control
while (!clrAdjusted);
}
if (!haveRenderInfo || riBack.IsEmpty)
{
nmcd->clrTextBk = ColorTranslator.ToWin32(_odCacheBackColor);
}
else
{
nmcd->clrTextBk = ColorTranslator.ToWin32(riBack);
}
nmcd->clrTextBk = !haveRenderInfo || riBack.IsEmpty
? (COLORREF)ColorTranslator.ToWin32(_odCacheBackColor)
: (COLORREF)ColorTranslator.ToWin32(riBack);
}
if (!haveRenderInfo || subItemFont is null)
@ -3240,21 +3186,12 @@ public partial class ListView : Control
}
}
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 (Items.Count == 0)
{
return null;
}
public ListViewItem? FindItemWithText(string text) => Items.Count == 0
? null
: FindItemWithText(text, includeSubItemsInSearch: true, startIndex: 0, isPrefixSearch: true);
return FindItemWithText(text, true, 0, true);
}
public ListViewItem? FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex)
{
return FindItemWithText(text, includeSubItemsInSearch, startIndex, true);
}
public ListViewItem? FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex) =>
FindItemWithText(text, includeSubItemsInSearch, startIndex, isPrefixSearch: true);
public ListViewItem? FindItemWithText(string text, bool includeSubItemsInSearch, int startIndex, bool isPrefixSearch)
{
@ -3341,14 +3278,7 @@ public partial class ListView : Control
OnSearchForVirtualItem(sviEvent);
// NOTE: this will cause a RetrieveVirtualItem event w/o a corresponding cache hint event.
if (sviEvent.Index != -1)
{
return Items[sviEvent.Index];
}
else
{
return null;
}
return sviEvent.Index != -1 ? Items[sviEvent.Index] : null;
}
else
{
@ -3653,15 +3583,12 @@ public partial class ListView : Control
left = (int)portion
};
if (PInvokeCore.SendMessage(this, PInvoke.LVM_GETITEMRECT, (WPARAM)index, ref itemrect) == 0)
{
throw new ArgumentOutOfRangeException(
return PInvokeCore.SendMessage(this, PInvoke.LVM_GETITEMRECT, (WPARAM)index, ref itemrect) == 0
? throw new ArgumentOutOfRangeException(
nameof(index),
index,
string.Format(SR.InvalidArgument, nameof(index), index));
}
return itemrect;
string.Format(SR.InvalidArgument, nameof(index), index))
: (Rectangle)itemrect;
}
/// <summary>
@ -3685,12 +3612,9 @@ public partial class ListView : Control
left = 0
};
if (PInvokeCore.SendMessage(this, PInvoke.LVM_GETITEMRECT, (WPARAM)index, ref itemrect) == 0)
{
return Rectangle.Empty;
}
return itemrect;
return PInvokeCore.SendMessage(this, PInvoke.LVM_GETITEMRECT, (WPARAM)index, ref itemrect) == 0
? Rectangle.Empty
: (Rectangle)itemrect;
}
/// <summary>
@ -3736,12 +3660,12 @@ public partial class ListView : Control
top = subItemIndex
};
if (PInvokeCore.SendMessage(this, PInvoke.LVM_GETSUBITEMRECT, (WPARAM)itemIndex, ref itemrect) == 0)
{
throw new ArgumentOutOfRangeException(nameof(itemIndex), itemIndex, string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex));
}
return itemrect;
return PInvokeCore.SendMessage(this, PInvoke.LVM_GETSUBITEMRECT, (WPARAM)itemIndex, ref itemrect) == 0
? throw new ArgumentOutOfRangeException(
nameof(itemIndex),
itemIndex,
string.Format(SR.InvalidArgument, nameof(itemIndex), itemIndex))
: (Rectangle)itemrect;
}
private void GroupImageListChangedHandle(object? sender, EventArgs e)
@ -3784,15 +3708,9 @@ public partial class ListView : Control
pt = new Point(x, y)
};
int iItem;
if (SupportsListViewSubItems)
{
iItem = (int)PInvokeCore.SendMessage(this, PInvoke.LVM_SUBITEMHITTEST, (WPARAM)0, ref lvhi);
}
else
{
iItem = (int)PInvokeCore.SendMessage(this, PInvoke.LVM_HITTEST, (WPARAM)0, ref lvhi);
}
int iItem = SupportsListViewSubItems
? (int)PInvokeCore.SendMessage(this, PInvoke.LVM_SUBITEMHITTEST, (WPARAM)0, ref lvhi)
: (int)PInvokeCore.SendMessage(this, PInvoke.LVM_HITTEST, (WPARAM)0, ref lvhi);
ListViewItem? item = (iItem == -1) ? null : Items[iItem];
ListViewHitTestLocations location;
@ -3895,17 +3813,9 @@ public partial class ListView : Control
throw new ArgumentException(string.Format(SR.OnlyOneControl, ch.Text), nameof(ch));
}
int idx;
// in Tile view the ColumnHeaders collection is used for the Tile Information
// In Tile view the ColumnHeaders collection is used for the Tile Information
// recreate the handle in that case
if (IsHandleCreated && View != View.Tile)
{
idx = InsertColumnNative(index, ch);
}
else
{
idx = index;
}
int idx = IsHandleCreated && View != View.Tile ? InsertColumnNative(index, ch) : index;
// First column must be left aligned
@ -6968,14 +6878,7 @@ public partial class ListView : Control
nmlvif->iStart);
OnSearchForVirtualItem(sviEvent);
if (sviEvent.Index != -1)
{
m.ResultInternal = (LRESULT)sviEvent.Index;
}
else
{
m.ResultInternal = (LRESULT)(-1);
}
m.ResultInternal = sviEvent.Index != -1 ? (LRESULT)sviEvent.Index : (LRESULT)(-1);
}
}

Просмотреть файл

@ -553,41 +553,14 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
}
}
protected override Padding DefaultMargin
{
get { return Padding.Empty; }
}
protected override Padding DefaultMargin => Padding.Empty;
protected virtual DockStyle DefaultDock
{
get
{
return DockStyle.Top;
}
}
protected virtual DockStyle DefaultDock => DockStyle.Top;
protected virtual Padding DefaultGripMargin
{
get
{
if (_toolStripGrip is not null)
{
return _toolStripGrip.DefaultMargin;
}
else
{
return _defaultGripMargin;
}
}
}
protected virtual Padding DefaultGripMargin =>
_toolStripGrip is not null ? _toolStripGrip.DefaultMargin : _defaultGripMargin;
protected virtual bool DefaultShowItemToolTips
{
get
{
return true;
}
}
protected virtual bool DefaultShowItemToolTips => true;
[Browsable(false)]
[SRDescription(nameof(SR.ToolStripDefaultDropDownDirectionDescr))]
@ -692,8 +665,7 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
}
/// <summary>
/// Returns an owner window that can be used to
/// own a drop down.
/// Returns an owner window that can be used to own a drop down.
/// </summary>
internal virtual NativeWindow DropDownOwnerWindow
{
@ -1587,17 +1559,11 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
// check the type of the currently set renderer.
// types are cached as this may be called frequently.
if (_currentRendererType == ToolStripManager.s_professionalRendererType)
{
return ToolStripRenderMode.Professional;
}
if (_currentRendererType == ToolStripManager.s_systemRendererType)
{
return ToolStripRenderMode.System;
}
return ToolStripRenderMode.Custom;
return _currentRendererType == ToolStripManager.s_professionalRendererType
? ToolStripRenderMode.Professional
: _currentRendererType == ToolStripManager.s_systemRendererType
? ToolStripRenderMode.System
: ToolStripRenderMode.Custom;
}
set
{
@ -1809,22 +1775,10 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
_ => null,
};
protected internal virtual ToolStripItem CreateDefaultItem(string? text, Image? image, EventHandler? onClick)
{
if (text == "-")
{
return new ToolStripSeparator();
}
else
{
return new ToolStripButton(text, image, onClick);
}
}
protected internal virtual ToolStripItem CreateDefaultItem(string? text, Image? image, EventHandler? onClick) =>
text == "-" ? new ToolStripSeparator() : new ToolStripButton(text, image, onClick);
private void ClearAllSelections()
{
ClearAllSelectionsExcept(null);
}
private void ClearAllSelections() => ClearAllSelectionsExcept(null);
private void ClearAllSelectionsExcept(ToolStripItem? item)
{
@ -2597,27 +2551,11 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
}
}
protected override bool IsInputKey(Keys keyData)
{
ToolStripItem? item = GetSelectedItem();
if (item is not null && item.IsInputKey(keyData))
{
return true;
}
protected override bool IsInputKey(Keys keyData) =>
(GetSelectedItem() is { } item && item.IsInputKey(keyData)) || base.IsInputKey(keyData);
return base.IsInputKey(keyData);
}
protected override bool IsInputChar(char charCode)
{
ToolStripItem? item = GetSelectedItem();
if (item is not null && item.IsInputChar(charCode))
{
return true;
}
return base.IsInputChar(charCode);
}
protected override bool IsInputChar(char charCode) =>
(GetSelectedItem() is { } item && item.IsInputChar(charCode)) || base.IsInputChar(charCode);
private static bool IsPseudoMnemonic(char charCode, string text)
{
@ -2778,22 +2716,13 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
bool isControlTab =
(keyData & Keys.Control) == Keys.Control && (keyData & Keys.KeyCode) == Keys.Tab;
if (isControlTab && !TabStop && HasKeyboardInput)
if (isControlTab
&& !TabStop
&& HasKeyboardInput
&& ToolStripManager.SelectNextToolStrip(this, forward: (keyData & Keys.Shift) == Keys.None))
{
bool handled = false;
if ((keyData & Keys.Shift) == Keys.None)
{
handled = ToolStripManager.SelectNextToolStrip(this, forward: true);
}
else
{
handled = ToolStripManager.SelectNextToolStrip(this, forward: false);
}
if (handled)
{
return true;
}
// Handled
return true;
}
}
@ -2875,12 +2804,7 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
break;
}
if (retVal)
{
return retVal;
}
return base.ProcessDialogKey(keyData);
return retVal ? retVal : base.ProcessDialogKey(keyData);
}
internal virtual void ProcessDuplicateMnemonic(ToolStripItem item, char charCode)
@ -4563,36 +4487,33 @@ public partial class ToolStrip : ScrollableControl, IArrangedElement, ISupportTo
/// </param>
internal void UpdateToolTip(ToolStripItem? item, bool refresh = false)
{
if (ShowItemToolTips)
if (!ShowItemToolTips || (item == _currentlyActiveTooltipItem && !refresh) || ToolTip is null)
{
if ((item != _currentlyActiveTooltipItem || refresh) && ToolTip is not null)
return;
}
if (item != _currentlyActiveTooltipItem)
{
ToolTip.Hide(this);
if (!refresh)
{
if (item != _currentlyActiveTooltipItem)
{
ToolTip.Hide(this);
if(!refresh)
_currentlyActiveTooltipItem = item;
}
if (_currentlyActiveTooltipItem is not null && !GetToolStripState(STATE_DRAGGING))
{
Cursor? currentCursor = Cursor.Current;
if (currentCursor is not null)
{
Point cursorLocation = Cursor.Position;
cursorLocation.Y += Cursor.Size.Height - currentCursor.HotSpot.Y;
cursorLocation = WindowsFormsUtils.ConstrainToScreenBounds(new Rectangle(cursorLocation, s_onePixel)).Location;
ToolTip.Show(_currentlyActiveTooltipItem.ToolTipText,
this,
PointToClient(cursorLocation),
ToolTip.AutoPopDelay);
}
}
_currentlyActiveTooltipItem = item;
}
}
if (_currentlyActiveTooltipItem is not null && !GetToolStripState(STATE_DRAGGING) && Cursor.Current is { } currentCursor)
{
Point cursorLocation = Cursor.Position;
cursorLocation.Y += Cursor.Size.Height - currentCursor.HotSpot.Y;
cursorLocation = WindowsFormsUtils.ConstrainToScreenBounds(new Rectangle(cursorLocation, s_onePixel)).Location;
ToolTip.Show(
_currentlyActiveTooltipItem.ToolTipText,
this,
PointToClient(cursorLocation),
ToolTip.AutoPopDelay);
}
}
private void UpdateLayoutStyle(DockStyle newDock)

Просмотреть файл

@ -268,25 +268,13 @@ public partial class ToolStripDropDown : ToolStrip
}
}
protected override DockStyle DefaultDock
{
get
{
return DockStyle.None;
}
}
protected override DockStyle DefaultDock => DockStyle.None;
public override ToolStripDropDownDirection DefaultDropDownDirection
{
get
{
if (_childDropDownDirection == ToolStripDropDownDirection.Default)
{
return (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right;
}
return _childDropDownDirection;
}
get => _childDropDownDirection == ToolStripDropDownDirection.Default
? (RightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right
: _childDropDownDirection;
set
{
_childDropDownDirection = value;
@ -312,24 +300,9 @@ public partial class ToolStripDropDown : ToolStrip
remove => base.DockChanged -= value;
}
/// <summary>
/// Returns an owner window that can be used to
/// own a drop down.
/// </summary>
internal override NativeWindow DropDownOwnerWindow
{
get
{
// Re-use the drop down owner from our parenting
// tool strip if we can.
if (_ownerItem is not null && _ownerItem.Owner is not null)
{
return _ownerItem.Owner.DropDownOwnerWindow;
}
return base.DropDownOwnerWindow;
}
}
internal override NativeWindow DropDownOwnerWindow =>
// Re-use the drop down owner from our parenting tool strip if we can.
_ownerItem?.Owner is not null ? _ownerItem.Owner.DropDownOwnerWindow : base.DropDownOwnerWindow;
public bool DropShadowEnabled
{
@ -389,12 +362,7 @@ public partial class ToolStripDropDown : ToolStrip
}
// if the FONT isn't set, then return our owner item's font.
if (IsAutoGenerated && OwnerItem is not null)
{
return OwnerItem.Font;
}
return base.Font;
return IsAutoGenerated && OwnerItem is not null ? OwnerItem.Font : base.Font;
}
set => base.Font = value;
}
@ -493,38 +461,21 @@ public partial class ToolStripDropDown : ToolStrip
internal override Size ImageScalingSizeInternal
{
get
{
if (IsAutoGenerated && OwnerToolStrip is not null)
{
return OwnerToolStrip.ImageScalingSizeInternal;
}
return base.ImageScalingSizeInternal;
}
get => IsAutoGenerated && OwnerToolStrip is not null
? OwnerToolStrip.ImageScalingSizeInternal
: base.ImageScalingSizeInternal;
set => base.ImageScalingSizeInternal = value;
}
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 is not null)
{
return ownerToolStrip.KeyboardActive;
}
return base.KeyboardActive;
}
// Ripple up the chain until we get the topmost toolstrip (usually the main menu strip is the one we care about)
get => OwnerToolStrip is { } ownerToolStrip ? ownerToolStrip.KeyboardActive : base.KeyboardActive;
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 is not null)
if (OwnerToolStrip is { } ownerToolStrip)
{
ownerToolStrip.KeyboardActive = value;
}
@ -964,21 +915,11 @@ public partial class ToolStripDropDown : ToolStrip
}
}
internal override bool CanProcessMnemonic()
{
internal override bool CanProcessMnemonic() =>
// Don't let mnemonics act as keyboard input in IE in the internet.
if (!Application.MessageLoop)
{
return false;
}
Application.MessageLoop && base.CanProcessMnemonic();
return base.CanProcessMnemonic();
}
protected override AccessibleObject CreateAccessibilityInstance()
{
return new ToolStripDropDownAccessibleObject(this);
}
protected override AccessibleObject CreateAccessibilityInstance() => new ToolStripDropDownAccessibleObject(this);
protected override LayoutSettings? CreateLayoutSettings(ToolStripLayoutStyle style)
{
@ -1049,36 +990,21 @@ public partial class ToolStripDropDown : ToolStrip
{
Point screenPoint = Point.Empty;
if (_ownerItem is not null and ToolStripDropDownItem)
{
screenPoint = ((ToolStripDropDownItem)_ownerItem).DropDownLocation;
}
else
{
screenPoint = suggestedBounds.Location;
}
screenPoint = _ownerItem is ToolStripDropDownItem dropDownItem
? dropDownItem.DropDownLocation
: suggestedBounds.Location;
Rectangle suggestedScreenBounds = new(screenPoint, suggestedBounds.Size);
if (WorkingAreaConstrained)
{
dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(suggestedScreenBounds);
}
else
{
dropDownBounds = WindowsFormsUtils.ConstrainToScreenBounds(suggestedScreenBounds);
}
dropDownBounds = WorkingAreaConstrained
? WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(suggestedScreenBounds)
: WindowsFormsUtils.ConstrainToScreenBounds(suggestedScreenBounds);
}
else
{
Point parentClientPoint = Point.Empty;
if ((_ownerItem is not null) && (_ownerItem is ToolStripDropDownItem item) && (ParentInternal is not null))
{
parentClientPoint = ParentInternal.PointToClient(item.DropDownLocation);
}
else
{
parentClientPoint = suggestedBounds.Location;
}
parentClientPoint = (_ownerItem is ToolStripDropDownItem dropDownItem) && (ParentInternal is not null)
? ParentInternal.PointToClient(dropDownItem.DropDownLocation)
: suggestedBounds.Location;
dropDownBounds = new Rectangle(parentClientPoint, suggestedBounds.Size);
}
@ -1126,15 +1052,7 @@ public partial class ToolStripDropDown : ToolStrip
return dropDownBounds;
}
internal Size GetSuggestedSize()
{
if (AutoSize)
{
return GetPreferredSize(Size.Empty);
}
return Size;
}
internal Size GetSuggestedSize() => AutoSize ? GetPreferredSize(Size.Empty) : Size;
/// <summary>
/// Returns the ToolStrip from which all the dropdowns started from. This can be null.
@ -1468,26 +1386,13 @@ public partial class ToolStripDropDown : ToolStrip
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override bool ProcessDialogChar(char charCode)
{
protected override bool ProcessDialogChar(char charCode) =>
// Since we're toplevel and aren't a container control, we've got to do our own mnemonic handling.
if ((OwnerItem is null || OwnerItem.Pressed) && charCode != ' ' && ProcessMnemonic(charCode))
{
return true;
}
((OwnerItem is null || OwnerItem.Pressed) && charCode != ' ' && ProcessMnemonic(charCode))
|| base.ProcessDialogChar(charCode);
return base.ProcessDialogChar(charCode);
}
protected internal override bool ProcessMnemonic(char charCode)
{
if (!CanProcessMnemonic())
{
return false;
}
return base.ProcessMnemonic(charCode);
}
protected internal override bool ProcessMnemonic(char charCode) =>
CanProcessMnemonic() && base.ProcessMnemonic(charCode);
internal override void ProcessDuplicateMnemonic(ToolStripItem item, char charCode)
{
@ -1748,14 +1653,7 @@ public partial class ToolStripDropDown : ToolStrip
// Fire Closing Event
// Cancel is prepopulated based on AutoClose feature.
if (e.CloseReason != ToolStripDropDownCloseReason.CloseCalled)
{
e.Cancel = !AutoClose;
}
else
{
e.Cancel = false;
}
e.Cancel = e.CloseReason != ToolStripDropDownCloseReason.CloseCalled && !AutoClose;
try
{

Просмотреть файл

@ -557,15 +557,10 @@ public unsafe partial class NativeWindow : MarshalByRefObject, IWin32Window, IHa
/// <summary>
/// Returns the native window for the given handle, or null if the handle is not in our hash table.
/// </summary>
private static NativeWindow? GetWindowFromTable(HWND handle)
{
if (s_windowHandles.TryGetValue(handle, out GCHandle value) && value.IsAllocated)
{
return (NativeWindow?)value.Target;
}
return null;
}
private static NativeWindow? GetWindowFromTable(HWND handle) =>
s_windowHandles.TryGetValue(handle, out GCHandle value) && value.IsAllocated
? (NativeWindow?)value.Target
: null;
/// <summary>
/// Returns the handle from the given <paramref name="id"/> if found, otherwise returns