2016-12-24 85 views
5

我想在TextBox以下顯示ToolTip消息,但也希望它們右對齊。如何在C中對齊控件和工具提示消息的右邊緣#

我能夠將ToolTip消息定位在文本框的右邊緣,所以我試圖通過消息長度移動留言。

所以我試圖通過使用TextRenderer.MeasureText()來獲得字符串長度,但是位置有點偏離,如下所示。

current result

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

我試圖在MeasureText()函數不同的標誌,但它並沒有幫助,而且由於工具提示消息具有填充,我去TextFormatFlags.LeftAndRightPadding

需要明確的是,這是我想達到的目標:

desired output

+0

嘗試用myToolTip.Font替換SystemFonts.DefaultFont。 – Graffito

+0

@Graffito:沒有這樣的事情。當擁有者繪製工具提示時,可以決定使用哪個字體。 – TaW

+0

對不起,字體只在ToolTip.Draw事件中可用(OwnerDraw = true)。 – Graffito

回答

4

您可以將ToolTipOwnerDraw屬性設置爲true。然後你就可以控制工具提示的外觀Draw事件是這樣的:

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

enter image description here

1

工具提示的字體要比SystemFonts.DefaultFont更大,所以測量不正確。我不知道ToolTip字體的確切變量是什麼,但許多其他SystemFonts都配置爲Segoe UI/size 9,即我的PC中的Tooltip字體。另外,你必須添加6px的填充。

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.CaptionFont, textBox1.Size, TextFormatFlags.LeftAndRightPadding).Width; 
    textWidth += 6; 
    int toolTipTextPosition_X = textBox1.Size.Width - textWidth; 

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

爲了實現完美的控制,你可以自己繪製的提示與Tooltip.OwnerDraw和事件Tooltip.Draw,選擇字體,填充和外觀。

+0

謝謝,更改字體/大小也起作用。 –

相關問題