【发布时间】:2011-05-19 14:16:56
【问题描述】:
我在 winform 上有一个按钮 在各种操作中,按钮文本长度可能会很大..
我不想改变按钮大小(所以我将“Autosize”属性设置为 false)
当按钮文本被剪切时,如何在鼠标悬停时显示工具提示(完整的按钮文本)?
请注意,我不总是想要工具提示.....我只在按钮文本被剪切时才想要它
【问题讨论】:
标签: c# winforms button tooltip
我在 winform 上有一个按钮 在各种操作中,按钮文本长度可能会很大..
我不想改变按钮大小(所以我将“Autosize”属性设置为 false)
当按钮文本被剪切时,如何在鼠标悬停时显示工具提示(完整的按钮文本)?
请注意,我不总是想要工具提示.....我只在按钮文本被剪切时才想要它
【问题讨论】:
标签: c# winforms button tooltip
我认为您必须手动检查按钮大小的按钮上的文本长度
如果它大于你必须添加按钮运行时的工具提示属性
不要忘记通过从工具箱中拖动的方式在项目中添加 ToolTip 控件
谢谢
【讨论】:
希望这段代码对你有帮助
if (button1.Text.Length > Your button text length to be checked)
{
System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip(this.button1, this.button1.Text);
}
您必须在按钮鼠标悬停事件中编写这些代码
【讨论】:
替代方案:使用按钮的 AutoElipsis 属性为 True。
【讨论】:
我认为到目前为止的答案并不完全正确 - 渲染字符串的长度(当您还考虑按钮的尺寸时,这就是您所需要的)可能会因字体和您使用的字符而异.当这些字符不同时,使用诸如Microsoft Sans Serif 之类的比例字体将为包含相同字符数的字符串返回不同的尺寸,例如:
“iiiiiiiii”没有那么宽
“wwwwwwwww”。
您应该使用`Graphics 类的MeasureString 方法
Graphics grfx = Graphics.FromImage( new Bitmap( 1, 1 ) );
// Set a proportional font
button1.Font = new Font( "Microsoft Sans Serif", 8.25f, FontStyle.Regular );
SizeF bounds = grfx.MeasureString(
button1.Text,
button1.Font,
new PointF( 0, 0 ),
new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );
MessageBox.Show( "Text dimensions: " + bounds.Width + "x" + bounds.Height );
// Set a non-proportional font
button1.Font = new Font( "Courier New", 8.25f, FontStyle.Regular );
bounds = grfx.MeasureString(
button1.Text,
button1.Font,
new PointF( 0, 0 ),
new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );
MessageBox.Show( "Text dimensions: " + bounds.Width + "x" + bounds.Height );
【讨论】:
最佳实践就是这样
/// <summary>
/// Exibe texto do controle num tipo ToolTip do winform
/// </summary>
/// <param name="controle">Controle</param>
/// <param name="icon"></param>
public static void ShowTextToolTip(Control controle, ToolTipIcon icon)
{
try
{
var tooltip = new ToolTip();
tooltip.ToolTipIcon = icon;
controle.MouseHover += (k, args) => { tooltip.SetToolTip(controle, controle.Text); };
}
catch (Exception)
{
}
}
可以这样称呼...
ShowTextToolTip(MyControlTextBox,ToolTipIcon.None);
【讨论】: