如何向控件添加工具提示?

我想显示一个 ToolTip的时候,鼠标悬停在一个控件。

如何在代码中创建工具提示,以及如何在设计器中创建工具提示?

202397 次浏览

这里 是您的文章,介绍如何使用代码来完成这项工作

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");
}

将工具提示控件从工具箱拖到窗体上。实际上,除了名称之外,不需要给它任何其他属性。然后,在希望具有工具提示的控件的属性中,查找具有刚才添加的工具提示控件名称的新属性。默认情况下,当光标悬停在控件上时,它将提供一个工具提示。

  1. 将工具提示组件添加到窗体中
  2. 选择要为其提供工具提示的控件之一
  3. 打开属性网格(F4) ,在列表中可以找到一个名为“ ToolTip on toolTip1”的属性(或类似的属性)。在该属性上设置所需的工具提示文本。
  4. 对其他控制重复2-3
  5. 成交。

这里的技巧是,ToolTip 控件是 扩展器控制扩展器控制,这意味着它将扩展窗体上 其他控制的属性集。在幕后,这是通过像 Svetlozar 的答案那样生成代码实现的。还有其他以相同方式工作的控件(如 HelpProvider)。

只需订阅控件的 ToolTipTextNeeded 事件,然后返回 e.TooltipText,就简单多了。

C # 中的工具提示很容易添加到几乎所有的 UI 控件中。您不需要为此添加任何 MouseHover 事件。

这是如何做到这一点-

  1. 将一个工具提示对象添加到窗体中。一个对象足够整个窗体使用。 ToolTip toolTip = new ToolTip();

  2. 使用所需的文本将控件添加到工具提示中。

    toolTip.SetToolTip(Button1,"Click here");

我是这样做的: 只需将事件添加到任何控件,设置控件的标记,并添加一个条件来处理适当控件/标记的工具提示。

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);
}
}