Поделиться через


How to: Respond to Font Scheme Changes in a Windows Forms Application

It's come to my attention that the topic How to: Respond to Font Scheme Changes in a Windows Forms Application is missing its code examples. Ouch. My bad. Here is the code for this topic, which demonstrates how to change your application's font size dynamically when the user switches to Large or Extra Large Font in Windows XP.

C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace WinFormsAutoScaling
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Font = SystemFonts.IconTitleFont;
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

}

void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
if (e.Category == UserPreferenceCategory.Window)
{
this.Font = SystemFonts.IconTitleFont;
}
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
}
}
}

VB.NET:

Imports Microsoft.Win32

Public Class Form1
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
AddHandler SystemEvents.UserPreferenceChanged, New UserPreferenceChangedEventHandler(AddressOf SystemEvents_UserPreferenceChangesEventHandler)
End Sub

    Private Sub SystemEvents_UserPreferenceChangesEventHandler(ByVal sender As Object, ByVal e As UserPreferenceChangedEventArgs)
If (e.Category = UserPreferenceCategory.Window) Then
Me.Font = SystemFonts.IconTitleFont
End If
End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
RemoveHandler SystemEvents.UserPreferenceChanged, New UserPreferenceChangedEventHandler(AddressOf SystemEvents_UserPreferenceChangesEventHandler)
End Sub
End Class