PR

Geminiで作るWindowsテキストエディタ開発と公開手順

スポンサーリンク
Windowsアプリ開発 パソコン・ネット
Windowsアプリ開発

「自分好みの機能だけを備えたテキストエディタが欲しい」「生成AIを使ってWindowsアプリを自作してみたい」と思ったことはありませんか?

前回は無料のClaudeを使って写真へモザイクを入れるWindowsアプリを作成しましたが、今回はGemini(有料版)とVisual Studio Community(C#)を使い、オリジナルのテキストエディタ「KotoPad」を作成する手順を解説します。

今回作成するテキストエディタには、文章作成に便利な以下の機能を実装しています。

・テキストファイルの新規作成・開く・上書き保存・別名保存
・折り返し表示に対応した行番号の表示
・改行のあり/なしを切り替えられるリアルタイム文字数カウント
・メニュー上部からの文字サイズ変更

この記事では、Geminiへの具体的なプロンプト指示から、出力されたC#コードのリビルド・動作確認、日本語アプリ名とアイコンの設定、さらに配布用の実行ファイル(EXE)を書き出す方法までを順を追ってご紹介します。AIを活用したC#アプリ開発の参考に、ぜひ最後までご覧ください。

スポンサーリンク

Geminiへのプロンプト指示とC#コードの生成

Geminiの4Neonへ次のように指示します。

テキストエディタのアプリを作成します。必要な機能は次のとおりです。Visual Studio CommunityのC#で作成するためのコードを作成してください。最初にオリジナルのアプリ名を作成し、そのアプリ名をプロジェクト名に設定します。

機能

扱うファイルの種類はテキストファイル

行番号を表示する

文字数を常にメニューへ表示する、文字数は改行を含む場合と含まない場合をスイッチで切り替える

折り返し表示にする

メニュー上部に文字の大きさを変える項目を入れる

ファイルの保存は、上書きと別名保存

すると次のコードが10秒ほどで出力されました。

using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace KotoPad
{
    public partial class Form1 : Form
    {
        // UIコントロール
        private MenuStrip menuStrip;
        private ToolStripComboBox fontSizeCombo;
        private ToolStripButton includeNewLineSwitch;
        private ToolStripLabel charCountLabel;
        private RichTextBox editor;
        private LineNumberPanel lineNumberPanel;

        // ファイル管理用
        private string currentFilePath = string.Empty;
        private bool isModified = false;

        public Form1()
        {
            InitializeComponent();
            SetupUI();
            UpdateTitle();
            UpdateCharCount();
        }

        private void SetupUI()
        {
            // ウィンドウの基本設定
            this.Text = "KotoPad";
            this.Size = new Size(900, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // --- メニューバーの構築 ---
            menuStrip = new MenuStrip();

            // 1. ファイルメニュー
            var fileMenu = new ToolStripMenuItem("ファイル(&F)");

            var newItem = new ToolStripMenuItem("新規作成(&N)", null, OnNewFile)
            {
                ShortcutKeys = Keys.Control | Keys.N
            };
            var openItem = new ToolStripMenuItem("開く(&O)...", null, OnOpenFile)
            {
                ShortcutKeys = Keys.Control | Keys.O
            };
            var saveItem = new ToolStripMenuItem("上書き保存(&S)", null, OnSaveFile)
            {
                ShortcutKeys = Keys.Control | Keys.S
            };
            var saveAsItem = new ToolStripMenuItem("名前を付けて保存(&A)...", null, OnSaveAsFile)
            {
                ShortcutKeys = Keys.Control | Keys.Shift | Keys.S
            };
            var exitItem = new ToolStripMenuItem("終了(&X)", null, (s, e) => this.Close());

            fileMenu.DropDownItems.AddRange(new ToolStripItem[]
            {
                newItem, openItem, new ToolStripSeparator(), saveItem, saveAsItem, new ToolStripSeparator(), exitItem
            });

            // 2. 文字サイズ変更(メニュー上部)
            var fontSizeLabel = new ToolStripLabel("文字サイズ:")
            {
                Margin = new Padding(15, 0, 0, 0)
            };
            fontSizeCombo = new ToolStripComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Width = 65
            };
            fontSizeCombo.Items.AddRange(new object[] { "9", "10", "11", "12", "14", "16", "18", "20", "24", "28", "36" });
            fontSizeCombo.SelectedItem = "12";
            fontSizeCombo.SelectedIndexChanged += OnFontSizeChanged;

            // 3. 改行カウント切り替えスイッチ(右寄せ)
            includeNewLineSwitch = new ToolStripButton("改行を含む: ON")
            {
                CheckOnClick = true,
                Checked = true,
                Alignment = ToolStripItemAlignment.Right,
                DisplayStyle = ToolStripItemDisplayStyle.Text,
                BackColor = Color.FromArgb(220, 235, 252)
            };
            includeNewLineSwitch.CheckedChanged += OnIncludeNewLineChanged;

            // 4. 文字数表示(右寄せ)
            charCountLabel = new ToolStripLabel("文字数: 0")
            {
                Alignment = ToolStripItemAlignment.Right,
                Margin = new Padding(0, 0, 15, 0),
                Font = new Font("Yu Gothic UI", 9.5f, FontStyle.Bold)
            };

            menuStrip.Items.Add(fileMenu);
            menuStrip.Items.Add(fontSizeLabel);
            menuStrip.Items.Add(fontSizeCombo);
            menuStrip.Items.Add(charCountLabel);
            menuStrip.Items.Add(includeNewLineSwitch);

            // --- メインエリア(行番号+エディタ) ---
            var mainPanel = new Panel
            {
                Dock = DockStyle.Fill
            };

            // 行番号表示パネル
            lineNumberPanel = new LineNumberPanel
            {
                Dock = DockStyle.Left,
                Width = 50,
                BackColor = Color.FromArgb(242, 242, 242)
            };
            lineNumberPanel.Paint += OnLineNumberPaint;

            // テキストエディタ本体
            editor = new RichTextBox
            {
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.None,
                Font = new Font("Consolas", 12f),
                WordWrap = true, // 折り返し表示を有効化
                AcceptsTab = true,
                ScrollBars = RichTextBoxScrollBars.Vertical
            };

            editor.TextChanged += OnEditorTextChanged;
            editor.VScroll += (s, e) => lineNumberPanel.Invalidate();
            editor.Resize += (s, e) => lineNumberPanel.Invalidate();
            editor.FontChanged += (s, e) => lineNumberPanel.Invalidate();

            mainPanel.Controls.Add(editor);
            mainPanel.Controls.Add(lineNumberPanel);

            // フォームへ追加
            this.Controls.Add(mainPanel);
            this.Controls.Add(menuStrip);
            this.MainMenuStrip = menuStrip;

            // 終了時の未保存確認
            this.FormClosing += OnFormClosing;
        }

        // --- イベントハンドラ ---

        private void OnEditorTextChanged(object sender, EventArgs e)
        {
            if (!isModified)
            {
                isModified = true;
                UpdateTitle();
            }
            UpdateCharCount();
            lineNumberPanel.Invalidate();
        }

        private void OnFontSizeChanged(object sender, EventArgs e)
        {
            if (float.TryParse(fontSizeCombo.SelectedItem?.ToString(), out float newSize))
            {
                editor.Font = new Font(editor.Font.FontFamily, newSize);
                lineNumberPanel.Invalidate();
            }
        }

        private void OnIncludeNewLineChanged(object sender, EventArgs e)
        {
            if (includeNewLineSwitch.Checked)
            {
                includeNewLineSwitch.Text = "改行を含む: ON";
                includeNewLineSwitch.BackColor = Color.FromArgb(220, 235, 252);
            }
            else
            {
                includeNewLineSwitch.Text = "改行を含む: OFF";
                includeNewLineSwitch.BackColor = SystemColors.Control;
            }
            UpdateCharCount();
        }

        private void UpdateCharCount()
        {
            string text = editor.Text;
            int count = includeNewLineSwitch.Checked
                ? text.Length
                : text.Replace("\n", "").Replace("\r", "").Length;

            charCountLabel.Text = $"文字数: {count:N0}";
        }

        private void UpdateTitle()
        {
            string fileName = string.IsNullOrEmpty(currentFilePath)
                ? "無題"
                : Path.GetFileName(currentFilePath);
            string mark = isModified ? "*" : "";
            this.Text = $"{mark}{fileName} - KotoPad";
        }

        // --- 行番号の描画処理(折り返し表示対応) ---

        private void OnLineNumberPaint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(lineNumberPanel.BackColor);

            // 右端の境界線
            using (var borderPen = new Pen(Color.LightGray))
            {
                e.Graphics.DrawLine(borderPen, lineNumberPanel.Width - 1, 0, lineNumberPanel.Width - 1, lineNumberPanel.Height);
            }

            string text = editor.Text;
            int firstVisibleIndex = editor.GetCharIndexFromPosition(new Point(0, 0));
            int lastVisibleIndex = editor.GetCharIndexFromPosition(new Point(0, editor.ClientSize.Height));

            // 最初の表示文字より前にある改行の数を数えて開始行番号を求める
            int logicalLine = 1;
            for (int i = 0; i < firstVisibleIndex && i < text.Length; i++)
            {
                if (text[i] == '\n') logicalLine++;
            }

            using (var brush = new SolidBrush(Color.DimGray))
            {
                // テキストが空のときは「1」だけ表示
                if (text.Length == 0)
                {
                    DrawLineNumber(e.Graphics, brush, 1, 2);
                    return;
                }

                // 最初の表示文字が論理行の先頭であれば描画
                if (firstVisibleIndex == 0 || text[firstVisibleIndex - 1] == '\n')
                {
                    Point pos = editor.GetPositionFromCharIndex(firstVisibleIndex);
                    DrawLineNumber(e.Graphics, brush, logicalLine, pos.Y);
                }

                // 表示範囲内の改行を探して各論理行の先頭位置に行番号を描画
                for (int i = firstVisibleIndex; i <= lastVisibleIndex && i < text.Length; i++)
                {
                    if (text[i] == '\n')
                    {
                        logicalLine++;
                        int nextCharIndex = i + 1;
                        Point pos = editor.GetPositionFromCharIndex(nextCharIndex);
                        if (pos.Y >= -editor.Font.Height && pos.Y <= lineNumberPanel.Height)
                        {
                            DrawLineNumber(e.Graphics, brush, logicalLine, pos.Y);
                        }
                    }
                }
            }
        }

        private void DrawLineNumber(Graphics g, Brush brush, int lineNumber, int y)
        {
            string numStr = lineNumber.ToString();
            SizeF size = g.MeasureString(numStr, editor.Font);
            float x = lineNumberPanel.Width - size.Width - 8;
            g.DrawString(numStr, editor.Font, brush, x, y);
        }

        // --- ファイル操作(新規・開く・上書き保存・別名保存) ---

        private void OnNewFile(object sender, EventArgs e)
        {
            if (!ConfirmDiscardChanges()) return;

            editor.Clear();
            currentFilePath = string.Empty;
            isModified = false;
            UpdateTitle();
            UpdateCharCount();
            lineNumberPanel.Invalidate();
        }

        private void OnOpenFile(object sender, EventArgs e)
        {
            if (!ConfirmDiscardChanges()) return;

            using (var dialog = new OpenFileDialog())
            {
                dialog.Filter = "テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    editor.Text = File.ReadAllText(dialog.FileName, Encoding.UTF8);
                    currentFilePath = dialog.FileName;
                    isModified = false;
                    UpdateTitle();
                    UpdateCharCount();
                    lineNumberPanel.Invalidate();
                }
            }
        }

        private void OnSaveFile(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(currentFilePath))
            {
                OnSaveAsFile(sender, e);
                return;
            }

            File.WriteAllText(currentFilePath, editor.Text, Encoding.UTF8);
            isModified = false;
            UpdateTitle();
        }

        private void OnSaveAsFile(object sender, EventArgs e)
        {
            using (var dialog = new SaveFileDialog())
            {
                dialog.Filter = "テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*";
                dialog.DefaultExt = "txt";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(dialog.FileName, editor.Text, Encoding.UTF8);
                    currentFilePath = dialog.FileName;
                    isModified = false;
                    UpdateTitle();
                }
            }
        }

        private bool ConfirmDiscardChanges()
        {
            if (!isModified) return true;

            var result = MessageBox.Show(
                "変更内容を保存しますか?",
                "KotoPad",
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                OnSaveFile(this, EventArgs.Empty);
                return !isModified;
            }
            return result == DialogResult.No;
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ConfirmDiscardChanges())
            {
                e.Cancel = true;
            }
        }

        // ちらつき防止用のダブルバッファリング対応パネル
        private class LineNumberPanel : Panel
        {
            public LineNumberPanel()
            {
                this.DoubleBuffered = true;
            }
        }
    }
}

オリジナルのアプリ名(プロジェクト名)は 「KotoPad」です。

Visual Studio Communityを起動して、「新しいプロジェクトの作成」をクリックします。

Visual Studio Communityの起動画面
Visual Studio Communityの起動画面

テンプレートから 「Windows フォーム アプリ」(C#)を選択して「次へ」を押します。

Visual Studio Communityの起動画面
Visual Studio Communityの起動画面

プロジェクト名に KotoPad と入力して作成します。

Visual Studio Communityの起動画面

そのまま「作成」ボタンをクリックします。

すると最初の画面になります。

Visual Studio Communityの起動画面
Visual Studio Communityの起動画面

ソリューションエクスプローラーで Form1.cs を右クリックし、「コードの表示」 を開きます。

Visual Studio Communityの起動画面
Visual Studio Communityの起動画面

「コードの表示」 を開きます。

すると初期値のコードが表示されるので、先ほどGeminiが作成したコードを上書きします。(すべてのコードを置き換えます)

Visual Studio Communityの起動画面
Visual Studio Communityの起動画面

コードを上書きすると次のようになります。

スポンサーリンク

Visual Studioでリビルドして動作確認する手順

それでは動かしてみましょう。最初にリビルドしてエラーがないことを確認し、その後に右△の実行ボタンを押します。

次のように実行されれば成功です。これでWindowsアプリができました。この後は、アイコンを作成して実行ファイルを作成するだけです。

KotoPad
KotoPad

皆さんも、ぜひ動かしてみましょう。

スポンサーリンク

アプリの日本語名設定とオリジナルアイコンの作成

KotoPadも悪くないのですが、もっとオリジナルのかわいい日本語名にしましょう。そして、そのイメージに合ったアイコンも作成しましょう。もちろんGeminiでそのまま作成してもらいます。

このアプリの日本語名を作成してください。かわいい名前が良いです。そして、その後で、イメージにあったアプリ用のアイコンも作成してください。

いくつかアプリ名を作成して、その中で「ぽちっとメモ」に決定しました。またアイコン画像を作成し、アイコン変換サイトで16、24、32、48、64、128などのサイズが含まれるようにしておきます。

アイコン変換サイトは、次のサイトが簡単です。元画像をアップロードするだけで様々なサイズを作成してくれます。

favicon.icoファイル分析 | ファビコン中身の確認・抽出ツール
ファビコン(favicon.ico)ファイルの中身を無料で解析し、各サイズのアイコンを確認・抽出。

次にアプリの日本語名「ぽちっとメモ」に修正する方法をGeminiへ聞きます。

このアプリの日本語名を「ぽちっとメモ」へ変更します。コードを修正してください。

Geminiが作成したコードを、先ほどと同じようにForm1.csのコードへ上書きします。

using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace KotoPad
{
    public partial class Form1 : Form
    {
        private const string AppName = "ぽちっとメモ";

        // UIコントロール
        private MenuStrip menuStrip;
        private ToolStripComboBox fontSizeCombo;
        private ToolStripButton includeNewLineSwitch;
        private ToolStripLabel charCountLabel;
        private RichTextBox editor;
        private LineNumberPanel lineNumberPanel;

        // ファイル管理用
        private string currentFilePath = string.Empty;
        private bool isModified = false;

        public Form1()
        {
            InitializeComponent();
            SetupUI();
            UpdateTitle();
            UpdateCharCount();
        }

        private void SetupUI()
        {
            // ウィンドウの基本設定
            this.Text = AppName;
            this.Size = new Size(900, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // --- メニューバーの構築 ---
            menuStrip = new MenuStrip();

            // 1. ファイルメニュー
            var fileMenu = new ToolStripMenuItem("ファイル(&F)");

            var newItem = new ToolStripMenuItem("新規作成(&N)", null, OnNewFile)
            {
                ShortcutKeys = Keys.Control | Keys.N
            };
            var openItem = new ToolStripMenuItem("開く(&O)...", null, OnOpenFile)
            {
                ShortcutKeys = Keys.Control | Keys.O
            };
            var saveItem = new ToolStripMenuItem("上書き保存(&S)", null, OnSaveFile)
            {
                ShortcutKeys = Keys.Control | Keys.S
            };
            var saveAsItem = new ToolStripMenuItem("名前を付けて保存(&A)...", null, OnSaveAsFile)
            {
                ShortcutKeys = Keys.Control | Keys.Shift | Keys.S
            };
            var exitItem = new ToolStripMenuItem("終了(&X)", null, (s, e) => this.Close());

            fileMenu.DropDownItems.AddRange(new ToolStripItem[]
            {
                newItem, openItem, new ToolStripSeparator(), saveItem, saveAsItem, new ToolStripSeparator(), exitItem
            });

            // 2. 文字サイズ変更(メニュー上部)
            var fontSizeLabel = new ToolStripLabel("文字サイズ:")
            {
                Margin = new Padding(15, 0, 0, 0)
            };
            fontSizeCombo = new ToolStripComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Width = 65
            };
            fontSizeCombo.Items.AddRange(new object[] { "9", "10", "11", "12", "14", "16", "18", "20", "24", "28", "36" });
            fontSizeCombo.SelectedItem = "12";
            fontSizeCombo.SelectedIndexChanged += OnFontSizeChanged;

            // 3. 改行カウント切り替えスイッチ(右寄せ)
            includeNewLineSwitch = new ToolStripButton("改行を含む: ON")
            {
                CheckOnClick = true,
                Checked = true,
                Alignment = ToolStripItemAlignment.Right,
                DisplayStyle = ToolStripItemDisplayStyle.Text,
                BackColor = Color.FromArgb(220, 235, 252)
            };
            includeNewLineSwitch.CheckedChanged += OnIncludeNewLineChanged;

            // 4. 文字数表示(右寄せ)
            charCountLabel = new ToolStripLabel("文字数: 0")
            {
                Alignment = ToolStripItemAlignment.Right,
                Margin = new Padding(0, 0, 15, 0),
                Font = new Font("Yu Gothic UI", 9.5f, FontStyle.Bold)
            };

            menuStrip.Items.Add(fileMenu);
            menuStrip.Items.Add(fontSizeLabel);
            menuStrip.Items.Add(fontSizeCombo);
            menuStrip.Items.Add(charCountLabel);
            menuStrip.Items.Add(includeNewLineSwitch);

            // --- メインエリア(行番号+エディタ) ---
            var mainPanel = new Panel
            {
                Dock = DockStyle.Fill
            };

            // 行番号表示パネル
            lineNumberPanel = new LineNumberPanel
            {
                Dock = DockStyle.Left,
                Width = 50,
                BackColor = Color.FromArgb(242, 242, 242)
            };
            lineNumberPanel.Paint += OnLineNumberPaint;

            // テキストエディタ本体
            editor = new RichTextBox
            {
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.None,
                Font = new Font("Consolas", 12f),
                WordWrap = true, // 折り返し表示を有効化
                AcceptsTab = true,
                ScrollBars = RichTextBoxScrollBars.Vertical
            };

            editor.TextChanged += OnEditorTextChanged;
            editor.VScroll += (s, e) => lineNumberPanel.Invalidate();
            editor.Resize += (s, e) => lineNumberPanel.Invalidate();
            editor.FontChanged += (s, e) => lineNumberPanel.Invalidate();

            mainPanel.Controls.Add(editor);
            mainPanel.Controls.Add(lineNumberPanel);

            // フォームへ追加
            this.Controls.Add(mainPanel);
            this.Controls.Add(menuStrip);
            this.MainMenuStrip = menuStrip;

            // 終了時の未保存確認
            this.FormClosing += OnFormClosing;
        }

        // --- イベントハンドラ ---

        private void OnEditorTextChanged(object sender, EventArgs e)
        {
            if (!isModified)
            {
                isModified = true;
                UpdateTitle();
            }
            UpdateCharCount();
            lineNumberPanel.Invalidate();
        }

        private void OnFontSizeChanged(object sender, EventArgs e)
        {
            if (float.TryParse(fontSizeCombo.SelectedItem?.ToString(), out float newSize))
            {
                editor.Font = new Font(editor.Font.FontFamily, newSize);
                lineNumberPanel.Invalidate();
            }
        }

        private void OnIncludeNewLineChanged(object sender, EventArgs e)
        {
            if (includeNewLineSwitch.Checked)
            {
                includeNewLineSwitch.Text = "改行を含む: ON";
                includeNewLineSwitch.BackColor = Color.FromArgb(220, 235, 252);
            }
            else
            {
                includeNewLineSwitch.Text = "改行を含む: OFF";
                includeNewLineSwitch.BackColor = SystemColors.Control;
            }
            UpdateCharCount();
        }

        private void UpdateCharCount()
        {
            string text = editor.Text;
            int count = includeNewLineSwitch.Checked
                ? text.Length
                : text.Replace("\n", "").Replace("\r", "").Length;

            charCountLabel.Text = $"文字数: {count:N0}";
        }

        private void UpdateTitle()
        {
            string fileName = string.IsNullOrEmpty(currentFilePath)
                ? "無題"
                : Path.GetFileName(currentFilePath);
            string mark = isModified ? "*" : "";
            this.Text = $"{mark}{fileName} - {AppName}";
        }

        // --- 行番号の描画処理(折り返し表示対応) ---

        private void OnLineNumberPaint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(lineNumberPanel.BackColor);

            // 右端の境界線
            using (var borderPen = new Pen(Color.LightGray))
            {
                e.Graphics.DrawLine(borderPen, lineNumberPanel.Width - 1, 0, lineNumberPanel.Width - 1, lineNumberPanel.Height);
            }

            string text = editor.Text;
            int firstVisibleIndex = editor.GetCharIndexFromPosition(new Point(0, 0));
            int lastVisibleIndex = editor.GetCharIndexFromPosition(new Point(0, editor.ClientSize.Height));

            // 最初の表示文字より前にある改行の数を数えて開始行番号を求める
            int logicalLine = 1;
            for (int i = 0; i < firstVisibleIndex && i < text.Length; i++)
            {
                if (text[i] == '\n') logicalLine++;
            }

            using (var brush = new SolidBrush(Color.DimGray))
            {
                // テキストが空のときは「1」だけ表示
                if (text.Length == 0)
                {
                    DrawLineNumber(e.Graphics, brush, 1, 2);
                    return;
                }

                // 最初の表示文字が論理行の先頭であれば描画
                if (firstVisibleIndex == 0 || text[firstVisibleIndex - 1] == '\n')
                {
                    Point pos = editor.GetPositionFromCharIndex(firstVisibleIndex);
                    DrawLineNumber(e.Graphics, brush, logicalLine, pos.Y);
                }

                // 表示範囲内の改行を探して各論理行の先頭位置に行番号を描画
                for (int i = firstVisibleIndex; i <= lastVisibleIndex && i < text.Length; i++)
                {
                    if (text[i] == '\n')
                    {
                        logicalLine++;
                        int nextCharIndex = i + 1;
                        Point pos = editor.GetPositionFromCharIndex(nextCharIndex);
                        if (pos.Y >= -editor.Font.Height && pos.Y <= lineNumberPanel.Height)
                        {
                            DrawLineNumber(e.Graphics, brush, logicalLine, pos.Y);
                        }
                    }
                }
            }
        }

        private void DrawLineNumber(Graphics g, Brush brush, int lineNumber, int y)
        {
            string numStr = lineNumber.ToString();
            SizeF size = g.MeasureString(numStr, editor.Font);
            float x = lineNumberPanel.Width - size.Width - 8;
            g.DrawString(numStr, editor.Font, brush, x, y);
        }

        // --- ファイル操作(新規・開く・上書き保存・別名保存) ---

        private void OnNewFile(object sender, EventArgs e)
        {
            if (!ConfirmDiscardChanges()) return;

            editor.Clear();
            currentFilePath = string.Empty;
            isModified = false;
            UpdateTitle();
            UpdateCharCount();
            lineNumberPanel.Invalidate();
        }

        private void OnOpenFile(object sender, EventArgs e)
        {
            if (!ConfirmDiscardChanges()) return;

            using (var dialog = new OpenFileDialog())
            {
                dialog.Filter = "テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    editor.Text = File.ReadAllText(dialog.FileName, Encoding.UTF8);
                    currentFilePath = dialog.FileName;
                    isModified = false;
                    UpdateTitle();
                    UpdateCharCount();
                    lineNumberPanel.Invalidate();
                }
            }
        }

        private void OnSaveFile(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(currentFilePath))
            {
                OnSaveAsFile(sender, e);
                return;
            }

            File.WriteAllText(currentFilePath, editor.Text, Encoding.UTF8);
            isModified = false;
            UpdateTitle();
        }

        private void OnSaveAsFile(object sender, EventArgs e)
        {
            using (var dialog = new SaveFileDialog())
            {
                dialog.Filter = "テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*";
                dialog.DefaultExt = "txt";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(dialog.FileName, editor.Text, Encoding.UTF8);
                    currentFilePath = dialog.FileName;
                    isModified = false;
                    UpdateTitle();
                }
            }
        }

        private bool ConfirmDiscardChanges()
        {
            if (!isModified) return true;

            var result = MessageBox.Show(
                "変更内容を保存しますか?",
                AppName,
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                OnSaveFile(this, EventArgs.Empty);
                return !isModified;
            }
            return result == DialogResult.No;
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ConfirmDiscardChanges())
            {
                e.Cancel = true;
            }
        }

        // ちらつき防止用のダブルバッファリング対応パネル
        private class LineNumberPanel : Panel
        {
            public LineNumberPanel()
            {
                this.DoubleBuffered = true;
            }
        }
    }
}

動かすと、アプリ名が「ぽちっとメモ」に変わりましたね。

ぽちっとメモ

作成したアイコン「app.ico」は、アプリ本体と同じフォルダーへ入れます。ソリューションエクスプローラーのForm1.csを右クリックし、「エクスプローラーで開く」でアプリ本体のフォルダが表示されるので、そこへコピーしましょう。

アイコンの設定は、ソリューションエクスプローラーの「KotoPad」を右クリックし、下にあるプロパティを選び、Win32リソースのアイコン欄へ設定します。

アイコンの設定
アイコンの設定

ウィンドウのタイトルバーにも出すには、Form1.cs の「 this.Text = AppName;」の次の行に、次を追加します。

this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);

メニューからリビルドし、実行しましょう。

ぽちっとメモ
ぽちっとメモ

アイコンが設定されていれば成功です。

スポンサーリンク

配布用実行ファイル(EXE)の作成と書き出し方法

最後にWEBで公開したり、配布するための実行ファイル(EXEファイル)を作成しましょう。

ソリューションエクスプローラーの「KotoPad」を右クリックし「発行」をクリックします。ターゲットをフォルダーにして設定を進めて閉じます。

次の公開準備の画面になったら、「すべての設定を表示」をクリックします。

配置モード「自己完結」、ファイルの公開オプションを「単一ファイルの作成」にチェックし保存します。これで実行ファイルを作成する設定が終わりました。この後は「発行」をクリックすれば実行ファイルが作成されています。

タイトルとURLをコピーしました