dotnet / dotnet/winforms

Expose Control.IsFontSet publicly

Open
#10,192 3 comments 0 reactions 1 assignee Claimed by @JeremyKuhne View on GitHub
api-suggestion Font
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
20h 23m
Merged PRs (30d)
103

Description

### Background and motivation

There is an internal method `Control.IsFontSet()` which determines if the `Font` property has been explicitly set on the control. This is as opposed to the `Font` property returning the font of the parent control or `Control.DefaultFont`.

When dealing with scaling it is very useful to know if the `Font` has been explicitly set. This allows you to avoid scaling the font if it's unnecessary because the parent font is already scaled. Internally this is done by `Control` for DPI scaling, however we have scenarios where we want to scale based on other factors. We're currently using reflection to access `Control.IsFontSet()` to get the performance benefit, but this is clearly risky long-term and less performant due to reflection dispatch, boxing, lack of inlining, etc.

### API Proposal

```diff
namespace System.Windows.Forms;

public partial class Control
{
+ public bool IsFontSet { get; }
}
```

### API Usage

```csharp
private static void ScaleFonts(Control ctrl, float factor)
{
if (ctrl.HasChildren)
{
foreach (Control childCtrl in ctrl.Controls)
{
ScaleFonts(childCtrl, factor);
}
}

if (ctrl.IsFontSet)
{
var curFont = ctrl.Font;
ctrl.Font = new Font(curFont.FontFamily, curFont.Size * factor, curFont.Style, curFont.Unit,
curFont.GdiCharSet, curFont.GdiVerticalFont);
}
}
```

### Alternative Designs

An alternative design could be to leave `IsFontSet` as a method instead of a read-only property. Also, it could be made virtual.

Another possibility would be to expose font scaling APIs publicly, such as moving some of the logic in `Control.WmDpiChangedBeforeParent` into a `public void ScaleFont(float scaleFactor)` method. However, exposing `IsFontSet` is more generally useful beyond font scaling.

### Risks

This design has the risk that a descendent `Control` could completely override `Font` behaviors, making `IsFontSet` incorrect.

### Will this feature affect UI controls?

Yes, however, it should have no impact on VS design, accessibility, or localization.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.