C# 如何在工具提示中换行文字

C# 如何在工具提示中换行文字,c#,winforms,C#,Winforms,如何将需要显示在工具提示中的文字换行显示看起来不直接支持: 如何包装显示的工具提示? 下面是一个使用反射来 实现这一目标 [ DllImport( "user32.dll" ) ] private extern static int SendMessage( IntPtr hwnd, uint msg, int wParam, int lParam); object o = typeof( ToolTip ).InvokeMember( "Handle", BindingFlag

如何将需要显示在工具提示中的文字换行显示看起来不直接支持:

如何包装显示的工具提示?

下面是一个使用反射来 实现这一目标

[ DllImport( "user32.dll" ) ] 
private extern static int SendMessage( IntPtr hwnd, uint msg,
  int wParam, int lParam); 

object o = typeof( ToolTip ).InvokeMember( "Handle",
   BindingFlags.NonPublic | BindingFlags.Instance |
   BindingFlags.GetProperty, 
   null, myToolTip, null ); 
IntPtr hwnd = (IntPtr) o; 
private const uint TTM_SETMAXTIPWIDTH = 0x418;
SendMessage( hwnd, TTM_SETMAXTIPWIDTH, 0, 300 );
龚瑞德


另一种方法是创建一个自动包装的regexp

WrappedMessage := RegExReplace(LongMessage,"(.{50}\s)","$1`n")

这是我最近写的一篇文章,我知道它不是最好的,但很有效。您需要按如下方式扩展工具提示控件:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

public class CToolTip : ToolTip
{
   protected Int32 LengthWrap { get; private set; }
   protected Control Parent { get; private set; }
   public CToolTip(Control parent, int length)
      : base()
   {
    this.Parent = parent;
    this.LengthWrap = length;
   }

   public String finalText = "";
   public void Text(string text)
   {
      var tText = text.Split(' ');
      string rText = "";

      for (int i = 0; i < tText.Length; i++)
      {
         if (rText.Length < LengthWrap)
         {
           rText += tText[i] + " ";
         }
         else
         {
             finalText += rText + "\n";
             rText = tText[i] + " ";
         }

         if (tText.Length == i+1)
         {
             finalText += rText;
         }
      }
  }
      base.SetToolTip(Parent, finalText);
  }
}

您可以使用
e.ToolTipSize
属性设置工具提示的大小,这将强制换行:

public class CustomToolTip : ToolTip
{
    public CustomToolTip () : base()
    {
        this.Popup += new PopupEventHandler(this.OnPopup);
    }

    private void OnPopup(object sender, PopupEventArgs e) 
    {
        // Set custom size of the tooltip
        e.ToolTipSize = new Size(200, 100);
    }
}

对于WPF,可以使用TextWrapping属性:

<ToolTip>
    <TextBlock Width="200" TextWrapping="Wrap" Text="Some text" />
</ToolTip>


理想情况下,此处的幻数0x418应定义为与相应头文件Commctrl.h中使用的名称相同的常数:“private const uint TTM_SETMAXTIPWIDTH=0x418”-这使得谷歌搜索更多信息变得更容易。在Windows7中,我的经验是,这种黑客只会在操作系统中禁用视觉样式时解决问题。如何解决这种情况?1)指向windowsclient.net博客的链接无效。2) 对于
DllImport
3),需要
System.Runtime.InteropServices
在实例化ToolTip对象后运行代码。这看起来像是PHP代码或其他东西。这里是c#version:Regex rgx=new Regex(“({50}\\s)”);字符串WrappedMessage=rgx.Replace(长消息,“$1\n”);
<ToolTip>
    <TextBlock Width="200" TextWrapping="Wrap" Text="Some text" />
</ToolTip>