0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#のWindowsFormでタブ追加風のデザインにしたい

Posted at

1. はじめに

  • 標準のタブコントロールを使用して、ブラウザのようなタブ追加のイメージに近づけたい
  • Control.HandleCreatedイベントを使用してタブの横幅の最小サイズを変更したい

2. 開発環境

  • C#
  • .NET8
  • Visual Studio 2022
  • Windows 11

3. 画面イメージ

3.1. 変更前

  • 標準のタブコントロールのままだとタブ追加(+)の横幅が大きくなってしまう
    image.png

3.2. 変更後

  • タブの最小横幅を見直すことでブラウザに近いイメージになった
    image.png

4. ソースコード

4.1. デザイナー

  • タブコントロールにHandleCreatedイベントを追加する(最終行)
Form1.Designer.cs (抜粋)
    // 
    // tabControl1
    // 
    tabControl1.Controls.Add(tabPage1);
    tabControl1.Controls.Add(tabPage2);
    tabControl1.Controls.Add(tabPage3);
    tabControl1.Dock = DockStyle.Fill;
    tabControl1.Location = new Point(0, 0);
    tabControl1.Name = "tabControl1";
    tabControl1.Padding = new Point(16, 3);
    tabControl1.SelectedIndex = 0;
    tabControl1.Size = new Size(593, 378);
    tabControl1.TabIndex = 1;

    // HandleCreatedイベントを追加
    tabControl1.HandleCreated += TabControl1_HandleCreated;

4.2. Form

  • HandleCreatedイベントを実装し、タブの最小横幅を16に変更する
  • 実際のタブ追加の処理までは未実装のため、別途追加する必要がある
Form1.cs
using System.Runtime.InteropServices;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // タブのサイズを変更
            this.tabControl1.ItemSize = new Size(240, 40);
        }

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
        private const int TCM_SETMINTABWIDTH = 0x1300 + 49;
        private void TabControl1_HandleCreated(object sender, EventArgs e)
        {
            SendMessage(tabControl1.Handle, TCM_SETMINTABWIDTH, IntPtr.Zero, (IntPtr)16);
        }
    }
}

5. 参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?