rksoftware

Visual Studio とか C# とかが好きです

まだまだ現役! .NET 6.0 でも Windows フォームアプリケーションの新機能

.NET 6.0 でもみんな大好き Windows フォームアプリケーションは現役です。新機能も追加されます。

参考:

今回はこの追加されたアプリケーション全体のデフォルトフォントを試してみます。

環境準備

Visual Studio 2022 Preview をインストールします。
https://visualstudio.microsoft.com/ja/vs/preview/vs2022/

.NET 6.0 の Preview を単独でインストールしても良いのですが、せっかくなので、Visual Studio もインストールしておきましょう。Visual Studio のインストールで .NET もインストールされます。

検証プロジェクトを作成

デフォルトフォントの異なる二つのプロジェクトを作りたいので、Windows フォームアプリケーションのプロジェクトを二つ作ります。

dotnet new sln -n Forms
dotnet new winforms -n Forms1
dotnet new winforms -n Forms2
dotnet sln add .\Forms1\Forms1.csproj
dotnet sln add .\Forms2\Forms2.csproj

プロジェクトテンプレートで生まれる Program.cs

プロジェクトテンプレートで次の Program.cs ファイルが作られました。デフォルトフォントの指定をここで行います。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Forms1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

デフォルトフォントの指定

こんな感じで行うらしいです。

Application.SetDefaultFont(new System.Drawing.Font("Yu Gothic", 24f));

このコードを組み込んで見ます。
同時に、テンプレートの状態では画面に何も表示されないので Label を一個おいてみます。

次のようになりました。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Forms1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // ここを追加
            Application.SetDefaultFont(new System.Drawing.Font("Yu Gothic", 24f));
            var form = new Form1();
            form.Controls.Add(new Label { AutoSize = true, Text = "埼玉群馬茨城" );

            Application.Run(form);
        }
    }
}

もう一つのプロジェクトでも

もう一つのプロジェクトでは別のフォントでデフォルト指定してみます。

Application.SetDefaultFont(new System.Drawing.Font("MS Gothic", 36f));
var form = new Form1();
form.Controls.Add(new Label { AutoSize = true, Text = "埼玉群馬茨城" );

実行

二つのプロジェクトを同時に実行してみます。

f:id:rksoftware:20210704224733j:plain

期待通り! フォントが異なっています。実際便利!

.NET 5 や .NET Framework では

TargetFramework を .NET 5 や .NET Framework にしてみるとエラーになります。

f:id:rksoftware:20210704224758j:plain

f:id:rksoftware:20210704224813j:plain

Error    CS0117  'Application' does not contain a definition for 'SetDefaultFont'

まとめ

皆が愛してくれる限り Windows フォームは滅びません。