我希望在鼠标悬停在控件上时显示一个工具提示ToolTip
。
如何在代码和设计器中创建工具提示?
这里是您使用代码实现它的文章。
private void Form1_Load(object sender, System.EventArgs e)
{
// Create the ToolTip and associate with the Form container.
ToolTip toolTip1 = new ToolTip();
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;
// Set up the ToolTip text for the Button and Checkbox.
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}
toolTip1
变量超出范围也无所谓了? - Svish从工具箱中将工具提示控件拖到您的表单上。除名称外,您实际上不需要给它任何属性。然后,在要在其上显示工具提示的控件的属性中,查找一个名为刚刚添加的工具提示控件名称的新属性。当光标悬停在控件上时,默认情况下将提供工具提示。
这里的诀窍是ToolTip控件是一个扩展器控件,它将扩展表单上其他控件的属性集。在背后,这是通过生成像Svetlozar回答中的代码来实现的。还有其他以相同方式工作的控件(如HelpProvider
)。
C# 中的工具提示非常容易添加到几乎所有的UI控件中,您不需要为此添加任何MouseHover事件。
以下是添加工具提示的步骤:
在您的表单中添加一个ToolTip对象。一个对象就足够整个表单使用。
ToolTip toolTip = new ToolTip();
使用所需的文本将控件添加到工具提示中。
toolTip.SetToolTip(Button1,"点击这里");
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}