MouseMove イベントを使用すると、マウスが置かれている項目のインデックスを追跡し、MouseMove 間で値を保持する変数にこれを格納できます。MouseMove がトリガーされるたびに、インデックスが変更されたかどうかを確認します。その場合、ツールチップを無効にし、このコントロールのツールチップ テキストを変更してから、再度アクティブにします。
次の例では、Car クラスの単一のプロパティが ListBox に表示されますが、いずれかの行にカーソルを合わせると完全な情報が表示されます。この例を機能させるために必要なのは、MouseMove イベントを持つ lstCars という ListBox と、WinForm 上の tt1 という ToolTip テキスト コンポーネントだけです。
車のクラスの定義:
class Car
{
// Main properties:
public string Model { get; set; }
public string Make { get; set; }
public int InsuranceGroup { get; set; }
public string OwnerName { get; set; }
// Read only property combining all the other informaiton:
public string Info { get { return string.Format("{0} {1}\nOwner: {2}\nInsurance group: {3}", Make, Model, OwnerName, InsuranceGroup); } }
}
フォーム読み込みイベント:
private void Form1_Load(object sender, System.EventArgs e)
{
// Set up a list of cars:
List<Car> allCars = new List<Car>();
allCars.Add(new Car { Make = "Toyota", Model = "Yaris", InsuranceGroup = 6, OwnerName = "Joe Bloggs" });
allCars.Add(new Car { Make = "Mercedes", Model = "AMG", InsuranceGroup = 50, OwnerName = "Mr Rich" });
allCars.Add(new Car { Make = "Ford", Model = "Escort", InsuranceGroup = 10, OwnerName = "Fred Normal" });
// Attach the list of cars to the ListBox:
lstCars.DataSource = allCars;
lstCars.DisplayMember = "Model";
}
ツールチップ コード (hoveredIndex というクラス レベル変数の作成を含む):
// Class variable to keep track of which row is currently selected:
int hoveredIndex = -1;
private void lstCars_MouseMove(object sender, MouseEventArgs e)
{
// See which row is currently under the mouse:
int newHoveredIndex = lstCars.IndexFromPoint(e.Location);
// If the row has changed since last moving the mouse:
if (hoveredIndex != newHoveredIndex)
{
// Change the variable for the next time we move the mouse:
hoveredIndex = newHoveredIndex;
// If over a row showing data (rather than blank space):
if (hoveredIndex > -1)
{
//Set tooltip text for the row now under the mouse:
tt1.Active = false;
tt1.SetToolTip(lstCars, ((Car)lstCars.Items[hoveredIndex]).Info);
tt1.Active = true;
}
}
}