コントロールにツールチップを表示する

マウスポインタを重ねたときに、ツールチップが表示されるようにする。
フォームデザイナを使用して設定を行う。まずボタンを二つ配置する。

これらボタンにマウスポインタを持っていくと、ツールチップを表示するようにしたい。WindowsフォームのツールボックスにあるToolTipをデザイナ画面にドラッグする。

次に、ツールチップを表示させたいコントロールを選択する。この場合、ボタンなのでButton1をまずクリックする。すると、Button1のプロパティ項目の一番下に「Misc」「ToolTip on toolTip1」という項目があるので、そこに文字列を入力する。この文字列がツールチップに表示されるものとなる。

続けて、Button2をクリックして選択すると、そのプロパティの一番下の項目に同じく「ToolTip on toolTip1」があるので、そこに文字列を入力する。この文字列がツールチップに表示されるものとなる。

実行例は以下の通り。二つのボタンそれぞれで設定した文字列がツールチップに表示されている。

このサンプルのソースコードは以下の通り。

import System.Drawing
import System.Drawing.Printing
import System.Windows.Forms

from System.Drawing import *
from System.Drawing.Printing import *
from System.Windows.Forms import *

class MainForm(Form):
    def __init__(self):
        self.InitializeComponent()
   
    def InitializeComponent(self):
        self._components = System.ComponentModel.Container()
        self._button1 = System.Windows.Forms.Button()
        self._button2 = System.Windows.Forms.Button()
        self._toolTip1 = System.Windows.Forms.ToolTip(self._components)
        self.SuspendLayout()
        #
        # button1
        #
        self._button1.Font = System.Drawing.Font("メイリオ", 9, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128)
        self._button1.Location = System.Drawing.Point(50, 25)
        self._button1.Name = "button1"
        self._button1.Size = System.Drawing.Size(180, 45)
        self._button1.TabIndex = 2
        self._button1.Text = "Button1"
        self._toolTip1.SetToolTip(self._button1, "This is Button1.")
        self._button1.UseVisualStyleBackColor = True
        #
        # button2
        #
        self._button2.Font = System.Drawing.Font("メイリオ", 9, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128)
        self._button2.Location = System.Drawing.Point(50, 90)
        self._button2.Name = "button2"
        self._button2.Size = System.Drawing.Size(180, 49)
        self._button2.TabIndex = 3
        self._button2.Text = "Button2"
        self._toolTip1.SetToolTip(self._button2, "No, this is button2.")
        self._button2.UseVisualStyleBackColor = True
        #
        # MainForm
        #
        self.ClientSize = System.Drawing.Size(283, 163)
        self.Controls.Add(self._button2)
        self.Controls.Add(self._button1)
        self.Name = "MainForm"
        self.Text = "Test"
        self.ResumeLayout(False)