- C#
WinForms入門|C#でWindowsフォームを作る手順とAnchor早見表
結論
WinForms は、C# で Windows の画面をデザイナーで作る .NET の仕組みです。
この記事でわかること
- 部品・イベント・DataGridView の書き方
- Designer.cs と .resx の中身と読み方
- Anchor・Dock の伸び方と移行の手順
疑問ごとの短い答えです。1列目は各節へのリンクです。
| 知りたいこと | 答え |
|---|---|
| WinForms とは | Windows の画面を作る .NET の 仕組み。部品とイベントで書く |
| 作り方 | VS 2026 の テンプレートか dotnet new winforms |
| 部品 | Button・TextBox・ ComboBox・DataGridView |
| 表の表示 | DataGridView の DataSource に BindingSource を渡す |
| 伸ばす | Anchor・Dock・ TableLayoutPanel |
| 移行 | 4.7.2 以上・SDK 形式に そろえてから .NET 10 へ |
| 選び方 | 既存の資産と要件で選ぶ |
確認環境:WinForms の仕様と移行は Microsoft Learn(英語版・日本語版)、期限は .NET のサポート ポリシー、VS Community の条件は公式ページで確かめました。C# の例は Learn の API の説明に沿って書いています。Windows Forms の画面の動作はこの環境では確かめていない。手元では Ubuntu 24.04.5 LTS・Python 3.13・GNU diffutils 3.10 で、記事の例の Designer.cs・.resx・.csproj をテキストと XML として読んで一覧と差分を出し、Anchor と Dock の配置は dotnet/winforms の DefaultLayout の決まりを Python で再現して計算しました(確認日 2026年12月1日)。
本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。
(記載例)出典:株式会社RJC「WinForms入門|C#でWindowsフォームを作る手順とAnchor早見表」
Windows フォーム(WinForms)とは|C# で GUI を作る仕組み
この節では、WinForms が何で、どんな作り方をするのかが分かります。
Windows フォーム(Windows Forms、略して WinForms)は、.NET で Windows 向けのデスクトップ画面を組み立てる UI フレームワークです。 C# か Visual Basic で書き、Windows だけで動きます。
画面1枚が フォーム(Form)、その上に置くボタンや入力欄が コントロール(部品)です。ボタンを押すとイベントが起き、結び付けたメソッド(イベント ハンドラー)が動きます。Excel VBA のユーザーフォームに近い作り方です。
向いていること
入力・一覧の業務画面、社内ツール
気をつけること
画面の C# はデザイナーが生成し、増えると読みにくい
実装は2系統で、GitHub で公開され .NET 10 などで動く版と、.NET Framework 4 に含まれる版があります。新しい改善は .NET 版に入ります。土台の .NET と .NET Framework の違いは、関連記事「.NET Frameworkとは|.NETとの違い・バージョン確認・サポート期限」で扱っています。次の節では、WinForms の将来を見ます。
Windows Forms の将来とサポート|.NET 10 で続く改善
この節では、「WinForms は将来なくなるのか」に、公式の説明で答えます。
WinForms は非推奨ではありません。 Microsoft の Windows 開発者向け FAQ は「Is WinForms deprecated?」に No と答え、機能の更新が続くと書いています。要件に合うなら、既存のアプリは WinForms のまま使い続けてよいとも答えています。
.NET 10 では、.NET 9 で試験段階だったダークモードの Application.SetColorMode と、Form.ShowAsync・ShowDialogAsync が正式な API になりました。
期限があるのは WinForms を載せる .NET の版です。.NET 10(LTS)と .NET 11(STS)は2028年11月14日まで、.NET 8・9 は2026年11月10日で終わりました。次の節では、アプリを作る手順を見ます。
Windows フォームアプリケーションの作り方|Visual Studio 2026 と dotnet new winforms
この節では、Visual Studio とコマンドの両方で作る手順と、できるファイルの役割が分かります。
VS 2026 にワークロードを足す
Visual Studio Installer のワークロードで .NET デスクトップ開発(英語版は .NET desktop development)に印を付け、個別のコンポーネントの .NET 10 も入れる。
winforms で検索する
「新しいプロジェクトの作成」(Create a new project)で winforms と検索し、言語を C# にして Windows フォーム アプリ(英語版は Windows Forms App)を選ぶ。名前に「(.NET Framework)」が付く方は選ばない。
.NET 10 を指定する
「追加情報」(Additional information)の Framework の一覧で .NET 10.0 の LTS(英語版の表記は .NET 10.0 (Long Term Support))を選んで作る。Form1 のデザイナーが開く。
デザイナーの4つの画面です(「表示」〈View〉メニューから開ける)。
| 画面 | 役割 |
|---|---|
| ソリューション エクスプローラー | Solution Explorer。 ファイルとフォームの一覧 |
| フォーム デザイナー | Form Designer。 部品をドラッグで置く |
| ツールボックス | Toolbox。 置ける部品の一覧 |
| プロパティ | Properties。部品の設定。 Events のアイコンで イベントの一覧 |
コマンドで作るときは .NET SDK のテンプレート winforms を使います(クラスライブラリは winformslib)。デザイナーは Visual Studio の機能なので、画面を目で見て組むなら Visual Studio を使います。
dotnet new winforms -n StockLog
cd StockLog
dotnet run
できるのは Program.cs・Form1.cs・Form1.Designer.cs・.csproj です。ApplicationConfiguration.Initialize() は、.csproj の設定(高 DPI・フォントなど)からビルド時に作られます。[STAThread] が要るので、WinForms のテンプレートはトップレベル ステートメントを使いません。
namespace StockLog;
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
フォームに部品を置く|Button・TextBox・ComboBox・DataGridView
この節では、業務画面でよく使う部品と、名前の付け方が分かります。
部品はツールボックスからフォームへドラッグし、プロパティ ウィンドウで Name と Text を決めます。 Name はコードから呼ぶ名前、Text は画面に出る文字です。button1 のままにせず、種類の接頭辞を付けると、コードで迷いません。
| 部品(接頭辞) | プロパティ・イベント |
|---|---|
| Label(lbl) | Text・AutoSize |
| TextBox(txt) | Text・MaxLength/ TextChanged |
| Button(btn) | Text・Enabled/Click |
| ComboBox(cmb) | DataSource・DropDownStyle/ SelectedIndexChanged |
| CheckBox(chk) | Checked/ CheckedChanged |
| NumericUpDown (nud) | Value・Minimum・Maximum |
| DateTimePicker (dtp) | Value・Format |
| DataGridView (dgv) | DataSource・ReadOnly/ CellDoubleClick |
| MenuStrip・ StatusStrip | メニューと下の状態表示 |
ComboBox では、画面の文字は DisplayMember、内部で使う値は ValueMember に指定するプロパティから取り、選んだ値が SelectedValue に入ります。DropDownList にすると一覧に無い文字は打てません。
cmbWarehouse.DisplayMember = "Name";
cmbWarehouse.ValueMember = "Code";
cmbWarehouse.DataSource = new List<Warehouse>
{
new("T01", "東京倉庫"),
new("O01", "大阪倉庫"),
};
// 選んだ倉庫のコード("T01" など)
var code = (string?)cmbWarehouse.SelectedValue;
// Warehouse は別の所で public record Warehouse(string Code, string Name); と定義
List の基本操作は、関連記事「C# ListとDictionaryの使い方|追加・削除・検索・ループ早見表」で扱っています。次の節ではイベントを見ます。
イベントの書き方|Click・Load・FormClosing と +=
この節では、イベント ハンドラーの作り方と、コードで付け外しする書き方が分かります。
デザイナーでボタンをダブルクリックすると、Click のハンドラーが Form1.cs にでき、結び付けは Form1.Designer.cs に書かれます。 ほかのイベントは、プロパティの Events のアイコンの一覧でダブルクリックします。
private void btnAdd_Click(object sender, EventArgs e)
{
MessageBox.Show($"数量:{txtQty.Text}", "確認");
}
sender はイベントを出した部品、e はイベントの情報です。コードでは += で付け、-= で外します。共有のハンドラーは sender で見分けます。
public Form1()
{
InitializeComponent();
btnClear.Click += (s, e) => txtQty.Clear(); // ラムダ式で付ける
rdoIn.CheckedChanged += Kind_CheckedChanged; // 2つの部品で共有
rdoOut.CheckedChanged += Kind_CheckedChanged;
}
private void Kind_CheckedChanged(object? sender, EventArgs e)
{
if (sender is RadioButton { Checked: true } rb)
lblKind.Text = rb.Text; // 押された方の文字
}
フォームのイベントは決まった順に起きます。開くときは HandleCreated → BindingContextChanged → Load → VisibleChanged → Activated → Shown、閉じるときは Closing → FormClosing → Closed → FormClosed → Deactivate です。初期値は Load、閉じる前の確認は FormClosing で e.Cancel = true にします。.NET 10 では Closing・Closed は廃止の扱いです(WFDEV004)。イベントとデリゲートの関係は、関連記事「C# FuncとActionの使い方 デリゲート・ラムダ式との違いを図解」で扱っています。次の節では作例を見ます。
入力チェックとCSV保存の作例|入出庫の記録画面
この節では、品目と数量を入れて登録し、CSV に残して一覧に出す画面の、Form1.cs の全文が分かります。
要点は3つで、部品の配置は後の節の Designer.cs のとおりです。
1入力は TryParse で確かめる
数字でない・範囲外ならメッセージを出し、入力欄へ戻して return。
2保存先はドキュメント
Program Files の中は書き込めないことがある。
3一覧は BindingList に足す
行を足すと DataGridView に出る。
using System.ComponentModel;
using System.Text;
namespace StockLog;
public partial class Form1 : Form
{
private readonly BindingList<StockRecord> _records = new();
private readonly BindingSource _source = new();
private readonly string _csvPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "stock_log.csv");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbItem.DataSource = new[] { "A4用紙", "トナー", "封筒" };
_source.DataSource = _records;
dgvLog.DataSource = _source;
dgvLog.Columns[nameof(StockRecord.At)].HeaderText = "日時";
dgvLog.Columns[nameof(StockRecord.Item)].HeaderText = "品目";
dgvLog.Columns[nameof(StockRecord.Quantity)].HeaderText = "数量";
if (File.Exists(_csvPath))
{
foreach (var line in File.ReadLines(_csvPath, Encoding.UTF8).Skip(1))
{
var f = line.Split(',');
_records.Add(new StockRecord(DateTime.Parse(f[0]), f[1], int.Parse(f[2])));
}
}
lblCount.Text = $"{_records.Count} 件";
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtQty.Text, out var qty) || qty is < 1 or > 999)
{
MessageBox.Show("数量は 1〜999 の整数で入力します。", "入力の確認",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtQty.Focus();
txtQty.SelectAll();
return;
}
var record = new StockRecord(DateTime.Now, (string)cmbItem.SelectedItem!, qty);
if (!File.Exists(_csvPath))
{
File.WriteAllText(_csvPath, "日時,品目,数量" + Environment.NewLine, Encoding.UTF8);
}
File.AppendAllText(_csvPath,
$"{record.At:yyyy-MM-dd HH:mm:ss},{record.Item},{record.Quantity}{Environment.NewLine}",
Encoding.UTF8);
_records.Add(record);
lblCount.Text = $"{_records.Count} 件";
txtQty.Clear();
}
private void btnClose_Click(object sender, EventArgs e) => Close();
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (txtQty.TextLength > 0 &&
MessageBox.Show("入力中の数量があります。閉じますか?", "確認",
MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true; // 閉じるのをやめる
}
}
}
public record StockRecord(DateTime At, string Item, int Quantity);
次の節では DataGridView を見ます。
DataGridViewの使い方とデータバインド(BindingSource)
この節では、DataGridView にデータを出す2つの方法と、つなげるデータの種類が分かります。
DataGridView は、DataSource にデータを渡すと列を自動で作ります(AutoGenerateColumns の既定は true)。 Microsoft Learn は、ふつうは BindingSource を間に置くと説明しています。
| つなげるデータ | 例と動き |
|---|---|
| IList | List<T>・配列。 Add しても一覧は増えない |
| IBindingList | BindingList<T>。 足した行が一覧に出る |
| IListSource | DataTable・DataSet。 DB の結果をそのまま |
| IBindingListView | BindingSource。 並べ替え・絞り込みの窓口 |
データを持たずに dgvLog.Rows.Add("A4用紙", 10) と行を足す非バインドの使い方もありますが、データと表示が混ざります。列を自分で決めてバインドする例です。
// 列を自分で決める(自動の列を止める)
dgvLog.AutoGenerateColumns = false;
dgvLog.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(StockRecord.Item), HeaderText = "品目"
});
dgvLog.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = nameof(StockRecord.Quantity), HeaderText = "数量",
DefaultCellStyle = { Format = "N0", Alignment = DataGridViewContentAlignment.MiddleRight }
});
dgvLog.DataSource = _source;
// 品目で絞り込む(BindingSource に IBindingListView のデータを渡したとき)
// _source.Filter = "Item = 'トナー'";
デザイナーで列を作ると、列ごとの設定が Designer.cs に長く並びます。Filter は DataTable のような絞り込みに対応したデータでだけ効き、BindingList では効きません。
.Designer.csと.resxの役割|デザイナーが書くファイル
この節では、1つのフォームを作る3つのファイルの分担と、手で直すときの注意が分かります。
| ファイル | 中身と書く人 |
|---|---|
| Form1.cs | イベントの処理。 自分で書く |
| Form1. Designer.cs | 部品の作成と設定 (InitializeComponent)。 デザイナーが書く |
| Form1.resx | 画像・アイコン・訳語。 デザイナーが書く XML |
Form1.cs と Form1.Designer.cs は、同じ Form1 クラスを partial で2つに分けたものです。 コンストラクターの InitializeComponent() が Designer.cs のメソッドを呼び、部品を作って並べます。生成されたメソッドの上には「Required method for Designer support - do not modify the contents of this method with the code editor.」というコメントが付きます(dotnet/winforms のフォームと同じ文)。手で書き換えると、デザイナーが開けなくなることがあります。
フォームの .resx も、デザイナー以外で直した分は失われることがあると Visual Studio のドキュメントが注意しています。値が BinaryFormatter の形のこともあるので、信頼できるフォームだけを扱います。
いらなくなったハンドラーを消す
Microsoft Learn の手順のとおり
次の節では、これをテキストとして読みます。
Designer.csと.resxをPythonで読む|部品の一覧と差分
この節では、作例のフォームの Designer.cs 全文と、そこから部品とイベントを一覧にした結果、Anchor を足したときの差分が分かります。
Designer.cs は書き方の型が決まっており、テキストとして解析できます。 棚卸しや移行の見積もりに使えます。先に結果の要点です。
1部品8個・イベント4本
Controls.Add の順も Designer.cs に残る。この順が Dock の結果を左右する(再現)。
2差分は設定の行だけ
デザイナーの操作は Designer.cs の行の増減として Git に残る。
3翻訳は差分だけ
en.resx は5件で、無いキーは既定の値を使う。BinaryFormatter の値も見つかる。
作例のフォーム(Anchor を足した後)の全文です。
namespace StockLog;
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblItem = new System.Windows.Forms.Label();
this.cmbItem = new System.Windows.Forms.ComboBox();
this.lblQty = new System.Windows.Forms.Label();
this.txtQty = new System.Windows.Forms.TextBox();
this.btnAdd = new System.Windows.Forms.Button();
this.dgvLog = new System.Windows.Forms.DataGridView();
this.lblCount = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblItem
//
this.lblItem.Location = new System.Drawing.Point(12, 15);
this.lblItem.Name = "lblItem";
this.lblItem.Size = new System.Drawing.Size(40, 15);
this.lblItem.Text = "品目";
//
// cmbItem
//
this.cmbItem.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cmbItem.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbItem.Location = new System.Drawing.Point(60, 12);
this.cmbItem.Name = "cmbItem";
this.cmbItem.Size = new System.Drawing.Size(220, 23);
this.cmbItem.TabIndex = 0;
//
// lblQty
//
this.lblQty.Location = new System.Drawing.Point(12, 47);
this.lblQty.Name = "lblQty";
this.lblQty.Size = new System.Drawing.Size(40, 15);
this.lblQty.Text = "数量";
//
// txtQty
//
this.txtQty.Location = new System.Drawing.Point(60, 44);
this.txtQty.Name = "txtQty";
this.txtQty.Size = new System.Drawing.Size(80, 23);
this.txtQty.TabIndex = 1;
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(300, 11);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(88, 25);
this.btnAdd.TabIndex = 2;
this.btnAdd.Text = "登録";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// dgvLog
//
this.dgvLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgvLog.Location = new System.Drawing.Point(12, 80);
this.dgvLog.Name = "dgvLog";
this.dgvLog.ReadOnly = true;
this.dgvLog.Size = new System.Drawing.Size(376, 176);
this.dgvLog.TabIndex = 3;
//
// lblCount
//
this.lblCount.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lblCount.Location = new System.Drawing.Point(12, 270);
this.lblCount.Name = "lblCount";
this.lblCount.Size = new System.Drawing.Size(120, 15);
this.lblCount.Text = "0 件";
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.Location = new System.Drawing.Point(300, 265);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(88, 25);
this.btnClose.TabIndex = 4;
this.btnClose.Text = "閉じる";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(400, 300);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lblCount);
this.Controls.Add(this.dgvLog);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.txtQty);
this.Controls.Add(this.lblQty);
this.Controls.Add(this.cmbItem);
this.Controls.Add(this.lblItem);
this.Name = "Form1";
this.Text = "入出庫の記録";
this.Load += new System.EventHandler(this.Form1_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblItem;
private System.Windows.Forms.ComboBox cmbItem;
private System.Windows.Forms.Label lblQty;
private System.Windows.Forms.TextBox txtQty;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.DataGridView dgvLog;
private System.Windows.Forms.Label lblCount;
private System.Windows.Forms.Button btnClose;
}
部品とイベントを数える Python のスクリプトです(ファイルは読むだけ)。
import re, sys
src = open(sys.argv[1], encoding="utf-8").read()
src = re.sub(r"\s*\n\s*\|", " |", src) # 複数行に分かれた Anchor を1行に
types = dict((n, t) for t, n in re.findall(r"private System\.Windows\.Forms\.(\w+) (\w+);", src))
props = {n: {} for n in types}
events = []
for name, prop, value in re.findall(r"this\.(\w+)\.(\w+) = (.+);", src):
if name in props:
props[name][prop] = value
for name, ev, handler in re.findall(r"this\.(?:(\w+)\.)?(\w+) \+= new [\w.]+\(this\.(\w+)\);", src):
events.append((name or "Form1", ev, handler))
def short(v):
v = v.replace("System.Windows.Forms.AnchorStyles.", "").replace("System.Windows.Forms.", "")
v = re.sub(r"new System\.Drawing\.(Point|Size)\((\d+), (\d+)\)", r"\2,\3", v)
v = re.sub(r"^\(\(AnchorStyles\)\(+|\)+$", "", v)
return v.replace("(", "").replace(")", "").strip('"')
print(f"部品 {len(types)} 個 / イベント {len(events)} 本")
print("名前 型 位置 大きさ Anchor")
for n, t in types.items():
p = props[n]
print(f"{n:10}{t:14}{short(p.get('Location','')):10}{short(p.get('Size','')):10}{short(p.get('Anchor','Top | Left(既定)'))}")
print("イベント:")
for name, ev, handler in events:
print(f" {name}.{ev} -> {handler}")
$ python3 designer_inventory.py after/Form1.Designer.cs
部品 8 個 / イベント 4 本
名前 型 位置 大きさ Anchor
lblItem Label 12,15 40,15 Top | Left(既定)
cmbItem ComboBox 60,12 220,23 Top | Left | Right
lblQty Label 12,47 40,15 Top | Left(既定)
txtQty TextBox 60,44 80,23 Top | Left(既定)
btnAdd Button 300,11 88,25 Top | Right
dgvLog DataGridView 12,80 376,176 Top | Bottom | Left | Right
lblCount Label 12,270 120,15 Bottom | Left
btnClose Button 300,265 88,25 Bottom | Right
イベント:
btnAdd.Click -> btnAdd_Click
btnClose.Click -> btnClose_Click
Form1.Load -> Form1_Load
Form1.FormClosing -> Form1_FormClosing
Anchor を設定する前と後の Designer.cs を diff で比べると、5つの部品に Anchor の行が足されただけでした。
$ diff -u --label before/Form1.Designer.cs --label after/Form1.Designer.cs before/Form1.Designer.cs after/Form1.Designer.cs
--- before/Form1.Designer.cs
+++ after/Form1.Designer.cs
@@ -43,6 +43,8 @@
//
// cmbItem
//
+ this.cmbItem.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.cmbItem.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbItem.Location = new System.Drawing.Point(60, 12);
this.cmbItem.Name = "cmbItem";
@@ -65,6 +67,7 @@
//
// btnAdd
//
+ this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(300, 11);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(88, 25);
@@ -74,6 +77,9 @@
//
// dgvLog
//
+ this.dgvLog.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
this.dgvLog.Location = new System.Drawing.Point(12, 80);
this.dgvLog.Name = "dgvLog";
this.dgvLog.ReadOnly = true;
@@ -82,6 +88,7 @@
//
// lblCount
//
+ this.lblCount.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lblCount.Location = new System.Drawing.Point(12, 270);
this.lblCount.Name = "lblCount";
this.lblCount.Size = new System.Drawing.Size(120, 15);
@@ -89,6 +96,7 @@
//
// btnClose
//
+ this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.Location = new System.Drawing.Point(300, 265);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(88, 25);
Localizable を True にしたフォームでは、Text や位置も .resx に入り、言語ごとに Form1.en.resx ができます。例の2つのファイルです。
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="btnAdd.Text" xml:space="preserve">
<value>登録</value>
</data>
<data name="btnAdd.Location" type="System.Drawing.Point, System.Drawing">
<value>300, 11</value>
</data>
<data name="btnAdd.Size" type="System.Drawing.Size, System.Drawing">
<value>88, 25</value>
</data>
<data name="btnClose.Text" xml:space="preserve">
<value>閉じる</value>
</data>
<data name="lblItem.Text" xml:space="preserve">
<value>品目</value>
</data>
<data name="lblQty.Text" xml:space="preserve">
<value>数量</value>
</data>
<data name=">>btnAdd.Name" xml:space="preserve">
<value>btnAdd</value>
</data>
<data name=">>btnAdd.ZOrder" xml:space="preserve">
<value>3</value>
</data>
<data name="imageList1.ImageStream" type="System.Windows.Forms.ImageListStreamer, System.Windows.Forms" mimetype="application/x-microsoft.net.object.binary.base64">
<value>AAEAAAD/////</value>
</data>
<data name="$this.Text" xml:space="preserve">
<value>入出庫の記録</value>
</data>
</root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="btnAdd.Text" xml:space="preserve">
<value>Add</value>
</data>
<data name="btnAdd.Size" type="System.Drawing.Size, System.Drawing">
<value>96, 25</value>
</data>
<data name="btnClose.Text" xml:space="preserve">
<value>Close</value>
</data>
<data name="lblItem.Text" xml:space="preserve">
<value>Item</value>
</data>
<data name="$this.Text" xml:space="preserve">
<value>Stock log</value>
</data>
</root>
読むスクリプトと出力です。data の行が出力の1行ずつに対応します。
import sys
import xml.etree.ElementTree as ET
def load(path):
root = ET.parse(path).getroot()
head = {h.get("name"): h.findtext("value") for h in root.findall("resheader")}
data = {}
for d in root.findall("data"):
data[d.get("name")] = (d.findtext("value"), d.get("type"), d.get("mimetype"))
return head, data
base_path, *culture_paths = sys.argv[1:]
head, base = load(base_path)
print(f"{base_path}: {head['resmimetype']} 版 {head['version']} / data {len(base)} 件")
for name, (value, typ, mime) in base.items():
kind = (typ or "string").split(",")[0].split(".")[-1]
note = " ← BinaryFormatter で直列化された値" if mime == "application/x-microsoft.net.object.binary.base64" else ""
shown = value if len(value) <= 12 else value[:12] + "…"
print(f" {name:24} {kind:18} {shown}{note}")
for path in culture_paths:
_, data = load(path)
print(f"{path}: data {len(data)} 件(無いキーは {base_path} の値を使う)")
for name, (value, _, _) in data.items():
print(f" {name:24} {base.get(name, ('(既定に無い)',))[0]} -> {value}")
$ python3 read_resx.py Form1.resx Form1.en.resx
Form1.resx: text/microsoft-resx 版 2.0 / data 10 件
btnAdd.Text string 登録
btnAdd.Location Point 300, 11
btnAdd.Size Size 88, 25
btnClose.Text string 閉じる
lblItem.Text string 品目
lblQty.Text string 数量
>>btnAdd.Name string btnAdd
>>btnAdd.ZOrder string 3
imageList1.ImageStream ImageListStreamer AAEAAAD///// ← BinaryFormatter で直列化された値
$this.Text string 入出庫の記録
Form1.en.resx: data 5 件(無いキーは Form1.resx の値を使う)
btnAdd.Text 登録 -> Add
btnAdd.Size 88, 25 -> 96, 25
btnClose.Text 閉じる -> Close
lblItem.Text 品目 -> Item
$this.Text 入出庫の記録 -> Stock log
次の節ではレイアウトを見ます。
レイアウトの基本|Anchor・Dock・TableLayoutPanel
この節では、ウィンドウを広げたときに部品を追従させる3つの方法と、Anchor の値の早見表が分かります。
何も設定しないと、部品は左上からの位置(Location)と大きさ(Size)のまま動きません。 ウィンドウを広げると右と下が空くだけです。Anchor の既定は Top・Left、Dock の既定は None です。
| 設定 | ウィンドウを広げると |
|---|---|
| Anchor Top, Left(既定) | そのまま |
| Anchor Top, Right | 右の距離を保って動く |
| Anchor Top, Left, Right | 横に伸びる |
| Anchor 4辺すべて | 縦と横に伸びる |
| Anchor Bottom, Right | 右下の角について動く |
| Anchor None | 中央とのずれを保つ。 大きさはそのまま |
| Dock Top・Bottom | 上か下に付き、 横に伸びる |
| Dock Fill | 残りの場所を全部使う |
Anchor と Dock は同時に使えず、後から設定した方が効きます。入力欄が並ぶ画面は TableLayoutPanel の各セルに部品を1つずつ置くと崩れにくくなります。幅は ColumnStyles・RowStyles で、固定(Absolute)・割合(Percent)・中身に合わせる(AutoSize)から選びます。
var table = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 3 };
table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 60)); // ラベルの列
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); // 入力欄の列
table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
table.RowStyles.Add(new RowStyle(SizeType.AutoSize));
table.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // 一覧が残りを使う
cmbItem.Dock = DockStyle.Fill;
dgvLog.Dock = DockStyle.Fill;
table.Controls.Add(new Label { Text = "品目", AutoSize = true }, 0, 0);
table.Controls.Add(cmbItem, 1, 0);
table.Controls.Add(new Label { Text = "数量", AutoSize = true }, 0, 1);
table.Controls.Add(txtQty, 1, 1);
table.Controls.Add(dgvLog, 0, 2);
table.SetColumnSpan(dgvLog, 2);
Controls.Add(table);
ほかに、部品を流し込んで折り返す FlowLayoutPanel(ボタンの並び)と、境目をドラッグできる2枚のパネルの SplitContainer(左に一覧・右に詳細)があります。次の節では動きを計算で確かめます。
Anchor・Dockの伸び方をPythonで再現|400x300から600x420へ
この節では、作例のフォームを広げたときの各部品の位置と大きさと、Dock が重なる原因が分かります。
dotnet/winforms の DefaultLayout は、Anchor した辺との距離を保ち、左右(上下)とも Anchor が無い部品は中央とのずれを保ちます。その計算を Python で書き、Designer.cs を読んで 600x420 に広げたときの値を、拡大率100%として計算しました。結果を先に図で示します。
Anchor の伸び方(anchor_sim.py) dgvLog 576x296 (元は 376x176) 点線=元の 400x300 登録・閉じる(Right):右へ 200 cmbItem(Left, Right):幅 220 → 420 dgvLog(4辺):縦横に伸びる lblCount・閉じる(Bottom):下へ 120 Anchor なしの before では8つとも動かない再現では、Anchor が無い before の8つの部品はどれも動きません。 after では4辺に Anchor した一覧が 576x296 に伸び、右下のボタンは右へ200・下へ120 動いています。
import re, sys
src = open(sys.argv[1], encoding="utf-8").read()
src = re.sub(r"\s*\n\s*\|", " |", src)
names = re.findall(r"private System\.Windows\.Forms\.\w+ (\w+);", src)
W0, H0 = map(int, re.search(r"this\.ClientSize = new System\.Drawing\.Size\((\d+), (\d+)\)", src).groups())
def get(name, prop):
m = re.search(rf"this\.{name}\.{prop} = (.+);", src)
return m.group(1) if m else ""
def layout(x, w, near, far, d):
"""1方向の Anchor の計算。near=左(上)、far=右(下)。d=親の幅(高さ)の増減"""
if near and far:
return x, w + d # 両側の距離を保つ → 伸びる
if far:
return x + d, w # 右(下)の距離を保つ → 動く
if near:
return x, w # 左(上)の距離を保つ → そのまま
return x + int(d / 2), w # どちらも無し → 中央からのずれを保つ(0 に向けて切り捨て)
def run(W, H):
print(f"ClientSize {W0}x{H0} -> {W}x{H}")
for n in names:
x, y = map(int, re.search(r"Point\((\d+), (\d+)\)", get(n, "Location")).groups())
w, h = map(int, re.search(r"Size\((\d+), (\d+)\)", get(n, "Size")).groups())
a = get(n, "Anchor") or "Top | Left"
nx, nw = layout(x, w, "Left" in a, "Right" in a, W - W0)
ny, nh = layout(y, h, "Top" in a, "Bottom" in a, H - H0)
moved = "伸びる" if (nw, nh) != (w, h) else ("動く" if (nx, ny) != (x, y) else "そのまま")
print(f" {n:9} ({x},{y} {w}x{h}) -> ({nx},{ny} {nw}x{nh}) {moved}")
for size in sys.argv[2:]:
run(*map(int, size.split("x")))
$ python3 anchor_sim.py before/Form1.Designer.cs 600x420
ClientSize 400x300 -> 600x420
lblItem (12,15 40x15) -> (12,15 40x15) そのまま
cmbItem (60,12 220x23) -> (60,12 220x23) そのまま
lblQty (12,47 40x15) -> (12,47 40x15) そのまま
txtQty (60,44 80x23) -> (60,44 80x23) そのまま
btnAdd (300,11 88x25) -> (300,11 88x25) そのまま
dgvLog (12,80 376x176) -> (12,80 376x176) そのまま
lblCount (12,270 120x15) -> (12,270 120x15) そのまま
btnClose (300,265 88x25) -> (300,265 88x25) そのまま
$ python3 anchor_sim.py after/Form1.Designer.cs 600x420
ClientSize 400x300 -> 600x420
lblItem (12,15 40x15) -> (12,15 40x15) そのまま
cmbItem (60,12 220x23) -> (60,12 420x23) 伸びる
lblQty (12,47 40x15) -> (12,47 40x15) そのまま
txtQty (60,44 80x23) -> (60,44 80x23) そのまま
btnAdd (300,11 88x25) -> (500,11 88x25) 動く
dgvLog (12,80 376x176) -> (12,80 576x296) 伸びる
lblCount (12,270 120x15) -> (12,390 120x15) 動く
btnClose (300,265 88x25) -> (500,385 88x25) 動く
Dock は、Controls の後ろ(Z オーダーの奥)にある部品から順に場所を取ります。Fill はその時点で残る場所を全部使うので、先に場所を取ると後から貼り付くツールバーと重なります。
# Dock の並べ方の再現。Controls の後ろ(Z オーダーの奥)から順に場所を取る
def dock(controls, W, H):
left, top, right, bottom = 0, 0, W, H
placed = {}
for name, style, size in reversed(controls): # 最後に Add した部品から
if style == "Top":
placed[name] = (left, top, right - left, size); top += size
elif style == "Bottom":
placed[name] = (left, bottom - size, right - left, size); bottom -= size
elif style == "Left":
placed[name] = (left, top, size, bottom - top); left += size
elif style == "Right":
placed[name] = (right - size, top, size, bottom - top); right -= size
elif style == "Fill":
placed[name] = (left, top, right - left, bottom - top)
return placed
def overlap(a, b):
ax, ay, aw, ah = a; bx, by, bw, bh = b
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
cases = {
"A: Fill を最初に Add": [("dgvLog", "Fill", 0), ("toolStrip", "Top", 25), ("statusStrip", "Bottom", 22)],
"B: Fill を最後に Add": [("toolStrip", "Top", 25), ("statusStrip", "Bottom", 22), ("dgvLog", "Fill", 0)],
}
for label, controls in cases.items():
print(label, "(Controls の順:", ", ".join(c[0] for c in controls) + ")")
placed = dock(controls, 400, 300)
for name, (x, y, w, h) in placed.items():
print(f" {name:11} x={x} y={y} 幅={w} 高さ={h}")
hits = [(a, b) for a in placed for b in placed if a < b and overlap(placed[a], placed[b])]
print(" 重なり:", ", ".join(f"{a} と {b}" for a, b in hits) or "なし")
$ python3 dock_order.py
A: Fill を最初に Add (Controls の順: dgvLog, toolStrip, statusStrip)
statusStrip x=0 y=278 幅=400 高さ=22
toolStrip x=0 y=0 幅=400 高さ=25
dgvLog x=0 y=25 幅=400 高さ=253
重なり: なし
B: Fill を最後に Add (Controls の順: toolStrip, statusStrip, dgvLog)
dgvLog x=0 y=0 幅=400 高さ=300
statusStrip x=0 y=278 幅=400 高さ=22
toolStrip x=0 y=0 幅=400 高さ=25
重なり: dgvLog と statusStrip, dgvLog と toolStrip
B の形になったら、Fill の部品で BringToFront()(デザイナーでは右クリックの Bring to Front)を使うと、Controls の先頭に移って A の形になります。次の節では高 DPI を見ます。
高DPI・ダークモード・フォントの設定
この節では、拡大率 150% などの画面で文字がぼやける・ずれるときの設定と、ダークモードの付け方が分かります。
.NET の WinForms では、高 DPI の動きを .csproj の ApplicationHighDpiMode で決めます。 既定は SystemAware で、起動時の主モニターの拡大率をすべてのモニターに使います。拡大率の違うモニターへウィンドウを動かすアプリは PerMonitorV2 にします。
| 値 | 動き |
|---|---|
| SystemAware (既定) | 主モニターの拡大率を 全モニターで使う |
| PerMonitorV2 | モニターごとに追従。 ダイアログなども |
| PerMonitor | モニターごとに追従 |
| DpiUnaware | 拡大しない (100% 扱い) |
| DpiUnawareGdiScaled | DpiUnaware に近い。 GDI の描画を補正 |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
</PropertyGroup>
</Project>
ApplicationDefaultFont(.NET 6 の説明では既定 Segoe UI, 9pt)と ApplicationVisualStyles(既定 true)も同じ所で決め、デザイナーもこの値を使います。.NET Framework 4.7 以降の WinForms では、app.config の DpiAwareness に PerMonitorV2 を書き、マニフェストで Windows 10 対応を宣言します(Windows 10 Creators Update 以降で効く)。
.NET 10 では、ダークモードを起動時の1行で付けられます。SystemColorMode.System は Windows の設定に合わせ、Classic(既定)は従来のライト、Dark は常にダークです。.NET 9 では試験段階で、WFO5001 の抑止が要りました。
ApplicationConfiguration.Initialize();
Application.SetColorMode(SystemColorMode.System);
Application.Run(new Form1());
次の節では移行を見ます。
.NET Frameworkの WinForms を .NET 10 へ移行する手順
この節では、移行の前にそろえることと、使えない部品、.csproj の確かめ方が分かります。
Microsoft Learn の移行ガイドは、GitHub Copilot のモダナイズのエージェントを推奨のツールとしています。 手で進めるときも準備を先に済ませます。
- 1Visual Studio を対象の .NET に対応した版にする.NET 10 なら Visual Studio 2026
- 2.NET Framework 4.7.2 以上へ上げるプロジェクトのプロパティで対象を変え、ビルドして直す
- 3packages.config を PackageReference へpackages.config の右クリックから移行できる
- 4SDK 形式の .csproj にするFramework を対象にしたままできる安全な準備
- 5NuGet を新しくしてから .NET 10 へ.NET Standard 2.0 向けのパッケージを選ぶ
移行前の .csproj(従来の形式)と移行後の .csproj を Python で読み、準備の残りを出しました。移行後の .csproj は前の節のファイルです。
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<RootNamespace>StockLog</RootNamespace>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="Contoso.Report">
<HintPath>..\packages\Contoso.Report.1.2.0\lib\net46\Contoso.Report.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
import sys
import xml.etree.ElementTree as ET
def local(tag):
return tag.split("}")[-1] # 名前空間を外す
for path in sys.argv[1:]:
root = ET.parse(path).getroot()
els = list(root.iter())
text = {local(e.tag): (e.text or "").strip() for e in els}
items = [(local(e.tag), e.get("Include")) for e in els if e.get("Include")]
sdk = root.get("Sdk")
print(f"{path}: {'SDK 形式 (' + sdk + ')' if sdk else '従来の形式'}")
if sdk:
print(f" TargetFramework {text.get('TargetFramework')} / UseWindowsForms {text.get('UseWindowsForms', '(無し)')}"
f" / ApplicationHighDpiMode {text.get('ApplicationHighDpiMode', 'SystemAware(既定)')}")
print(f" ファイルを1つずつ並べた行: {sum(1 for k, _ in items if k in ('Compile', 'EmbeddedResource'))} 件")
continue
ver = text.get("TargetFrameworkVersion", "")
print(f" TargetFrameworkVersion {ver}")
print(f" ファイルを1つずつ並べた行: {sum(1 for k, _ in items if k in ('Compile', 'EmbeddedResource'))} 件")
todo = []
if tuple(map(int, ver.lstrip("v").split("."))) < (4, 7, 2):
todo.append("先に .NET Framework 4.7.2 以上へ上げる")
if ("None", "packages.config") in items:
todo.append("packages.config を PackageReference へ移す")
todo.append("SDK 形式の .csproj に変える(Framework のままでも可)")
if ("Reference", "System.Configuration") in items:
todo.append("System.Configuration は NuGet の System.Configuration.ConfigurationManager へ")
for i, t in enumerate(todo, 1):
print(f" 移行の前に {i}. {t}")
$ python3 check_csproj.py StockLog.Framework.csproj StockLog.csproj
StockLog.Framework.csproj: 従来の形式
TargetFrameworkVersion v4.6.1
ファイルを1つずつ並べた行: 4 件
移行の前に 1. 先に .NET Framework 4.7.2 以上へ上げる
移行の前に 2. packages.config を PackageReference へ移す
移行の前に 3. SDK 形式の .csproj に変える(Framework のままでも可)
移行の前に 4. System.Configuration は NuGet の System.Configuration.ConfigurationManager へ
StockLog.csproj: SDK 形式 (Microsoft.NET.Sdk)
TargetFramework net10.0-windows / UseWindowsForms true / ApplicationHighDpiMode PerMonitorV2
ファイルを1つずつ並べた行: 0 件
SDK 形式は .cs と .resx を自動で集めるので0件です。app.config は NuGet の System.Configuration.ConfigurationManager で .NET でも読め、WCF・レジストリなどは Microsoft.Windows.Compatibility にあります。
.NET Framework の時代の部品の一部は、.NET では作れません。 .NET 10 では、.NET Framework 向けのライブラリを読み込むためだけに型が残され、WFDEV006 の警告が出ます。
| 使えない部品 | 代わりの部品 |
|---|---|
| DataGrid | DataGridView |
| MainMenu | MenuStrip |
| ContextMenu | ContextMenuStrip |
| Menu | ToolStripDropDown・ ToolStripDropDownMenu |
| StatusBar | StatusStrip |
| ToolBar | ToolStrip |
.NET のフォームのデザイナーは、Visual Studio とは別のプロセス(DesignToolsServer.exe)で動きます。Framework 各版の期限は .NET Framework の記事にあります。
WinFormsか別の技術か|要件別の選び方とExcel VBAからの移り方
この節では、WinForms を軸に、やりたいことごとの選び方と、VBA のユーザーフォームとの対応が分かります。
| やりたいこと | 向く技術 |
|---|---|
| 既存の WinForms を 保守して延ばす | WinForms のまま .NET 10 へ |
| Excel VBA の 入力画面を置き換える | WinForms |
| 画面と処理を分けて テストする | WPF(XAML と Binding・MVVM) |
| 既存の画面に Web の UI を足す | Blazor Hybrid (.NET 版のみ) |
新しい汎用アプリは WinUI 3、Windows 以外も対象なら .NET MAUI が候補です。Blazor Hybrid は、FAQ によれば .NET Framework のアプリでは使えません。Excel VBA のユーザーフォームから移るときは、書き方が次のように対応します。
| 用途 | VBA | WinForms(C#) |
|---|---|---|
| 開く | UserForm1. Show | ShowDialog()・ Show() |
| 閉じる | Unload Me | Close() |
| 初期化 | UserForm_ Initialize | Load イベント |
| 閉じる前 | UserForm_ QueryClose | FormClosing |
| 入力値 | TextBox1. Value | txtQty.Text |
| 一覧に足す | ListBox1. AddItem | Items.Add |
| メッセージ | MsgBox | MessageBox. Show |
| 動かす PC | Excel が要る | .NET の ランタイム |
大きな違いはデータの置き場で、VBA はシート、WinForms は CSV やデータベースに置き、画面とデータが分かれます。VBA 側のイベントの順は、関連記事「VBAユーザーフォームの作り方|入力・登録・閉じるまでコード付き」で扱っています。次の節ではエラーを見ます。
よくあるエラーと直し方(別スレッド・デザイナー・廃止の部品)
この節では、WinForms で出るエラーの原文と、原因・直し方が分かります。
| エラー・症状 | 原因・直し方 |
|---|---|
Cross-thread operation not valid | 別スレッドから 部品を触った。 await の後か Invoke で |
| CS1061 (ハンドラーが無い) | Form1.cs だけ 消した。イベントを リセットする |
| WFDEV006 | 廃止の部品。 表の代わりの部品へ |
| PlatformNotSupportedException | BinaryFormatter を使った。 .NET 9 以降で出る |
| WFO5001・ WFO5002 | .NET 9 の試験段階の API。 .NET 10 では出ない |
| 広げても 部品が動かない | Anchor が既定。 Anchor か表で組む |
| Fill の一覧が ツールバーに隠れる | Z オーダーの順。 一覧を BringToFront() |
| 文字がぼやける・ ずれる | 高 DPI の設定。 PerMonitorV2 にする |
別スレッドのエラーの全文は「Cross-thread operation not valid. Control accessed from a thread other than the thread it was created on.」です(Microsoft Learn)。重い処理は Task.Run に出して await し、await の後で部品を触ります。.NET 9 以降は Control.InvokeAsync もあります。
private async void btnLoad_Click(object sender, EventArgs e)
{
btnLoad.Enabled = false;
lblCount.Text = "読み込み中…";
var rows = await Task.Run(() => LoadRecords()); // 別スレッドで読む
_source.DataSource = new BindingList<StockRecord>(rows); // ここは UI スレッド
lblCount.Text = $"{rows.Count} 件";
btnLoad.Enabled = true;
}
BackgroundWorker は互換のために残るもので、Learn は async と await を勧めています。await の後で元のスレッドに戻る仕組みとデッドロックは、関連記事「C# async/awaitの使い方|Taskとデッドロック回避をコードで解説」で扱っています。
作った後の確かめです。
- 1部品の Name を接頭辞つきにしたかbutton1 のままにしない
- 2広げて崩れないかAnchor・Dock・TableLayoutPanel
- 3重い処理で画面が固まらないかawait Task.Run(…) で待つ
- 4Designer.cs を手で書き換えていないか直すのはデザイナーで
よくある質問
この節では、Windows フォームを始めるときの疑問に答えます。
Q. Windows フォームと WinForms は同じものですか?
同じです。Windows Forms の略が WinForms で、日本語版の Visual Studio では「Windows フォーム アプリ」と出ます。
Q. Visual Studio が無いと WinForms は作れませんか?
.NET SDK があれば dotnet new winforms で作ってビルドできます。画面を目で見て組むデザイナーは Visual Studio の機能です。
Q. フォームを2つ作って、別の画面を開くには?
プロジェクトに「フォーム (Windows フォーム)」(Form (Windows Forms))を足し、using var f = new EditForm(); f.ShowDialog(this); で開きます。ShowDialog は閉じるまで元の画面を触れず、Show は両方を触れます。
Q. Anchor と Dock はどちらを使えばよいですか?
端からの距離を保って伸ばすなら Anchor、上下左右の端や残りの場所に貼り付けるなら Dock です。同時には効かず、後から設定した方が効きます。入力欄が並ぶ画面は TableLayoutPanel の中で Dock = Fill にします。
Q. Designer.cs を手で直して、デザイナーが開かなくなったら?
Git などで直す前の版に戻すのが確実です。手で足したい処理は、Form1.cs のコンストラクターの InitializeComponent() の後に書きます。
Q. C# で GUI を作る方法は WinForms のほかに何がありますか?
Microsoft のものでは WPF・WinUI 3・.NET MAUI です(選び方)。
Q. Visual Studio Community は会社で使えますか?
条件によります。PC が250台超か年間売上100万米ドル超の組織は、オープンソース・研究・授業を除いて使えず、それ以外の組織は5人までです(公式ページ)。
Q. 作ったアプリをほかの PC で動かすには?
Visual Studio の「発行」(Publish)か dotnet publish で配り、.NET のデスクトップ ランタイムを入れてもらうか、同梱する自己完結の形にします。大きさは .NET Framework の記事の publish の節にあります。
Q. Excel VBA と WinForms は並べて使えますか?
使えます。マクロを残し、入力の画面だけを WinForms にして CSV やデータベースでつなぐ形で、1つずつ移せます。
まとめ
この節では、記事の要点を5行で振り返ります。
- WinForms は部品を置いてイベントを書く、Windows 向けの画面の仕組み。非推奨ではなく、.NET 10 は2028年11月14日まで。
- Visual Studio 2026 の「Windows フォーム アプリ」で .NET 10 を選ぶか、
dotnet new winforms。.csproj は UseWindowsForms と net10.0-windows。 - 一覧は BindingList → BindingSource → DataGridView。入力は TryParse で確かめる。
- Designer.cs と .resx はデザイナーが書く。テキストと XML として読めるので、棚卸しと差分のレビューに使える。
- 伸ばすのは Anchor・Dock・TableLayoutPanel。Dock は Z オーダーの奥から場所を取る。移行は 4.7.2・PackageReference・SDK 形式の順に準備する。
参考・出典
確認日はいずれも 2026年12月1日です。
- Microsoft Learn「Desktop Guide (Windows Forms .NET)」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/overview/
- Microsoft Learn「Tutorial: Create a Windows Forms app with .NET」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/get-started/create-app-visual-studio
- Microsoft Learn「.NET default templates for dotnet new」:https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new-sdk-templates
- Microsoft Learn「How to handle a control event」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-add-an-event-handler
- Microsoft Learn「Order of events in Windows Forms」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/order-of-events-in-windows-forms
- Microsoft Learn「Position and layout of controls」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/layout
- Microsoft Learn「Control.Dock Property」:https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.dock
- Microsoft Learn「Control.Anchor Property」:https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.anchor
- Microsoft Learn「DataGridView control overview」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/datagridview-control-overview-windows-forms
- Microsoft Learn「How to bind data to the DataGridView control」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control
- Microsoft Learn「Designers changes from .NET Framework」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls-design/designer-differences-framework
- Microsoft Learn「Windows Forms Designer overview」(Visual Studio):https://learn.microsoft.com/en-us/visualstudio/designers/windows-forms-designer-overview
- Microsoft Learn「MSBuild reference for .NET Desktop SDK projects」:https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props-desktop
- Microsoft Learn「What's new in Windows Forms for .NET 6」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/whats-new/net60
- Microsoft Learn「What's new in Windows Forms for .NET 9」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/whats-new/net90
- Microsoft Learn「What's new in Windows Forms for .NET 10」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/whats-new/net100
- Microsoft Learn「High DPI support in Windows Forms」(.NET Framework):https://learn.microsoft.com/en-us/dotnet/desktop/winforms/high-dpi-support-in-windows-forms
- Microsoft Learn「How to make thread-safe calls to controls」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls
- Microsoft Learn「Overview of upgrading Windows Forms apps」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/migration/
- Microsoft Learn「WFDEV006」:https://learn.microsoft.com/en-us/dotnet/desktop/winforms/wfdev-diagnostics/wfdev006
- Microsoft Learn「Windows developer FAQ」:https://learn.microsoft.com/en-us/windows/apps/get-started/windows-developer-faq
- .NET「.NET and .NET Core Support Policy」:https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core
- Visual Studio「Visual Studio Community」:https://visualstudio.microsoft.com/vs/community/
- .NET Source Browser「DefaultLayout.cs」(dotnet/winforms):https://source.dot.net/System.Windows.Forms/System/Windows/Forms/Layout/DefaultLayout.cs.html
- .NET Source Browser「MessageBoxes.Designer.cs」(dotnet/winforms のテスト用フォーム):https://source.dot.net/WinFormsControlsTest/MessageBoxes.Designer.cs.html
本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。
(記載例)出典:株式会社RJC「WinForms入門|C#でWindowsフォームを作る手順とAnchor早見表」
株式会社RJC ― SI事業・SES事業・AI駆動開発。RJCは一緒に成長を楽しめる会社です。
WE ARE HIRING
RJCで一緒に開発しながら、
成長を楽しみませんか?
RJCは、Web・モバイル・AIを活用した開発プロジェクトで、テックリードやPM・PMOも活躍するシステム開発会社です。会社を知る、待遇を確かめる、話を聞いてみる。気になるところ見てみてください!
- 127日年間休日
- 12時間平均残業時間
- 毎日ガチャ遊びココロも大切にする福利厚生。アマギフなどの賞品ラインナップ!
ほかにも、チケットレストラン、書籍読み放題、2年ごとの慰労報奨(休暇 or 金一封)、11期連続の黒字決算。