在文本框中的光标上显示工具提示
Display Tooltip over cursor in textbox
我正在 Winforms (.NET Framework 4.7.2) 中开发一个项目,并希望在文本框控件中的光标上方显示气泡工具提示。这是我目前拥有的:
这就是我想要的:
我已经尝试了SetToolTip()
和Tooltip.Show()
两种方法,但我无法使工具提示显示在文本框光标上。 我该如何完成?
您可以使用 win32 函数 GetCaretPos
获取光标(插入符号)位置,然后将该位置传递给 ToolTip.Show()
方法。
首先,将以下内容添加到您的 class (preferably, a separate static class for native methods):
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCaretPos(out Point lpPoint);
然后,你可以这样做:
ToolTip tTip = new ToolTip();
tTip.IsBalloon = true;
tTip.ToolTipIcon = ToolTipIcon.Error;
tTip.ToolTipTitle = "Your title";
Point p;
if (GetCaretPos(out p))
{
// This is optional. Removing it causes the arrow to point at the top of the line.
int yOffset = textBox1.Font.Height;
p.Y += yOffset;
// Calling .Show() two times because of a known bug in the ToolTip control.
// See:
tTip.Show(string.Empty, textBox1, 0);
tTip.Show("Your message here", textBox1, p, 1000);
}
注:
我调用了 ToolTip.Show()
方法两次,第一次使用空字符串且持续时间为 0 毫秒,因为 ToolTip 控件中的一个已知错误导致气球箭头未指向正确的位置第一次被调用。查看 this answer 了解更多信息。
我正在 Winforms (.NET Framework 4.7.2) 中开发一个项目,并希望在文本框控件中的光标上方显示气泡工具提示。这是我目前拥有的:
这就是我想要的:
我已经尝试了SetToolTip()
和Tooltip.Show()
两种方法,但我无法使工具提示显示在文本框光标上。 我该如何完成?
您可以使用 win32 函数 GetCaretPos
获取光标(插入符号)位置,然后将该位置传递给 ToolTip.Show()
方法。
首先,将以下内容添加到您的 class (preferably, a separate static class for native methods):
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCaretPos(out Point lpPoint);
然后,你可以这样做:
ToolTip tTip = new ToolTip();
tTip.IsBalloon = true;
tTip.ToolTipIcon = ToolTipIcon.Error;
tTip.ToolTipTitle = "Your title";
Point p;
if (GetCaretPos(out p))
{
// This is optional. Removing it causes the arrow to point at the top of the line.
int yOffset = textBox1.Font.Height;
p.Y += yOffset;
// Calling .Show() two times because of a known bug in the ToolTip control.
// See:
tTip.Show(string.Empty, textBox1, 0);
tTip.Show("Your message here", textBox1, p, 1000);
}
注:
我调用了 ToolTip.Show()
方法两次,第一次使用空字符串且持续时间为 0 毫秒,因为 ToolTip 控件中的一个已知错误导致气球箭头未指向正确的位置第一次被调用。查看 this answer 了解更多信息。