September 11, 2013

ToolTip Control in Windows Forms

Tooltip is often used as a hint or helper to tell application users what the functionality of a specific control is for or what will happen when they conduct operation on those controls, for instance, click a button.

In Windows Forms, you cannot set up the tooltip for a control until you drag a ToolTip control into the designer (you can create a ToolTip instance in the code though) and put your tooltip in the ToolTip on [ToolTip Control Name] property.




That being said, in some cases you will need to set up your tooltip PROGRAMMATICALLY. For example, in my case I want to display the tooltip on a button indicating a file path from a data source when the cursor hovers the button. We can leverage the ToolTip.Show method of the ToolTip control to assign the message being displayed to the button.
private void Button_OpenStonePhoto_MouseHover(object sender, EventArgs e)
{
    this.ToolTip_Photo.Show(@"C:\Users\Pete\Desktop\Pete.jpg", this.Button_OpenStonePhoto);
}

Alternatively, you can use the ToolTip.SetToolTip method to achieve the same, but note that the two methods have subtlety based on MSDN.
private void Form1_Load(object sender, EventArgs e)
{
    this.ToolTip_Photo.SetToolTip(this.Button_OpenStonePhoto, @"C:\Users\Pete\Desktop\Pete.jpg");
}

No comments: