コンテンツにスキップ

ファイルベース実行例3. File-based Apps で、WinForms デスクトップアプリ を作成する

Page ID: 1114988419001

最終更新日:

ファイルベース実行例3.
File-based Apps で、WinForms デスクトップアプリ を作成する

Section titled “ファイルベース実行例3. File-based Apps で、WinForms デスクトップアプリ を作成する”

統合開発環境 Visual Studio が無くとも、極論「 メモ帳 」と「 1つの C# ファイル 」だけで、
WinForms デスクトップアプリ を作って実行する… なんてことも、
File-based Apps で、実際にできてしまいます。
(茨の道ですが)。

Program.cs
#!/usr/bin/env dotnet
#:property TargetFramework=net11.0-windows
#:property LangVersion=preview
#:property Nullable=enable
#:property ImplicitUsings=enable
#:property PublishAot=false
#:property OutputType=WinExe
#:property UseWindowsForms=true
using System.Windows;
using System.ComponentModel;
/// <summary>メインエントリポイント</summary>
public static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetColorMode(SystemColorMode.Dark);
Application.Run(new MainForm());
}
}
/// <summary>メイン画面 コードビハインド</summary>
file partial class MainForm : Form
{
private int cnt = 0;
public MainForm()
=> InitializeComponent();
private void BtnAddCnt_Click(object? sender, EventArgs e)
=> this.LblCnt.Text = (++cnt).ToString();
}
/// <summary>メイン画面 デザイン</summary>
file partial class MainForm : Form
{
private IContainer? components = null;
private Label LblHelloWorld = new();
private Label LblCnt = new();
private Button BtnAddCnt = new();
private void InitializeComponent()
{
SuspendLayout();
this.LblHelloWorld.Name = "LblHelloWorld";
this.LblHelloWorld.Location = new Point(12, 12);
this.LblHelloWorld.Text = "Hello, World!";
this.LblHelloWorld.Font = new Font("HackGen Console NF", 10.5F);
this.LblHelloWorld.TabIndex = 0;
this.LblCnt.Name = "LblCnt";
this.LblCnt.Location = new Point(150, 56);
this.LblCnt.Text = "0";
this.LblCnt.Font = new Font("HackGen Console NF", 13.5F, FontStyle.Bold);
this.LblCnt.TabIndex = 1;
this.BtnAddCnt.Location = new Point(70, 92);
this.BtnAddCnt.Name = "BtnAppend";
this.BtnAddCnt.Size = new Size(180, 32);
this.BtnAddCnt.Text = "インクリメント";
this.BtnAddCnt.Font = new Font("HackGen Console NF", 12.0F);
this.BtnAddCnt.Click += BtnAddCnt_Click;
this.BtnAddCnt.TabIndex = 2;
this.Name = "MainForm";
this.ClientSize = new Size(320, 160);
this.AutoScaleDimensions = new SizeF(7F, 15F);
this.AutoScaleMode = AutoScaleMode.Font;
this.Text = "メイン画面 (WinForms)";
this.Controls.Add(this.LblHelloWorld);
this.Controls.Add(this.LblCnt);
this.Controls.Add(this.BtnAddCnt);
ResumeLayout(false);
}
protected override void Dispose(bool disposing)
{
if (disposing && components is not null)
components.Dispose();
base.Dispose(disposing);
}
}
シェル
$> dotnet Program.cs

コンパイル済みの実行ファイル (EXE) ではなく、
C#ソースコードを記述した、ただのテキストファイル 1つ をコマンドからキックしただけですが、
以下のように WinForms のウィンドウが表示されて、ちゃんと問題なく動作します。

C# ソースコード 100行弱 で、実現できてしまいましたが、
やはり WinForms のデザインを「メモ帳」だけで記述するのは、
正気の沙汰ではないですね…。

WPF や WinUI 3 などの GUI フレームワークの方が、適しているでしょう。