如何在C#中对齐控件和工具提示消息的右边缘 [英] How to align right edges of a control and ToolTip Message in C#

查看:141
本文介绍了如何在C#中对齐控件和工具提示消息的右边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 TextBox 下面显示 ToolTip 消息,但也希望它们正确对齐。



我能够将ToolTip消息放置在文本框的右边缘,所以我尝试将消息向左移动消息长度。



因此,我尝试使用 TextRenderer.MeasureText()来获取字符串长度,但是位置有点偏离,如下所示。



 私有无效button1_Click(对象发送者,EventArgs e)
{
ToolTip myToolTip = new ToolTip();

string test =这是一个测试字符串。
int textWidth = TextRenderer.MeasureText(test,SystemFonts.DefaultFont,textBox1.Size,TextFormatFlags.LeftAndRightPadding).Width;
int toolTipTextPosition_X = textBox1.Size.Width-textWidth;

myToolTip.Show(test,textBox1,toolTipTextPosition_X,textBox1.Size.Height);
}

我在 MeasureText()中尝试了不同的标志>函数,但没有帮助,并且由于ToolTip消息具有填充,我选择了 TextFormatFlags.LeftAndRightPadding



这就是我想要实现的目标:



解决方案

您可以设置


I want to display a ToolTip message below a TextBox, but also want them to be right aligned.

I was able to position the ToolTip message at the right edge of the textbox, so I tried to move the message left by message length.

So I tried to get the string length by using TextRenderer.MeasureText(), but the position is a little bit off as shown below.

private void button1_Click(object sender, EventArgs e)
{
   ToolTip myToolTip = new ToolTip();

   string test = "This is a test string.";
   int textWidth = TextRenderer.MeasureText(test, SystemFonts.DefaultFont, textBox1.Size, TextFormatFlags.LeftAndRightPadding).Width;
   int toolTipTextPosition_X = textBox1.Size.Width - textWidth;

   myToolTip.Show(test, textBox1, toolTipTextPosition_X, textBox1.Size.Height);
}

I tried with different flags in the MeasureText() function but it didn't help, and since ToolTip message has a padding, I went for TextFormatFlags.LeftAndRightPadding.

To be clear, this is what I would like to achieve:

解决方案

You can set OwnerDraw property of the ToolTip to true. Then you can control appearance and location of the tooltip in Draw event. In the following example, I've found the tooltip handle and moved it to the desired location using MoveWindow Windows API function :

[System.Runtime.InteropServices.DllImport("User32.dll")]
static extern bool MoveWindow(IntPtr h, int x, int y, int width, int height, bool redraw);
private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
{
    e.DrawBackground();
    e.DrawBorder();
    e.DrawText();
    var t = (ToolTip)sender;
    var h = t.GetType().GetProperty("Handle",
      System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    var handle = (IntPtr)h.GetValue(t);
    var c = e.AssociatedControl;
    var location = c.Parent.PointToScreen(new Point(c.Right - e.Bounds.Width, c.Bottom));
    MoveWindow(handle, location.X, location.Y, e.Bounds.Width, e.Bounds.Height, false);
}

这篇关于如何在C#中对齐控件和工具提示消息的右边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆