为长文本禁用 WinForms ListViewItem 工具提示

Disable WinForms ListViewItem Tooltip for long texts

我创建了 ListView 并添加了两个带有长文本的项目。 当我 select 第一项第二项的文本被剪裁时,例如 "MyIte....".

因此,当将鼠标指针移动到此项下方时,我会看到包含所有文本的工具提示。

如何禁用此工具提示?

设置属性ListView.ShowItemToolTips = false没有帮助。

ListView 在收到带有 TTN_NEEDTEXT lparam 的 WM_Notify 消息时显示项目工具提示。因此,要禁用工具提示,您可以处理 ListView 消息,如果控件收到该消息,则忽略它。

您可以继承您的 ListView 并覆盖 WndProc,但作为另一种选择,您可以注册一个 NativeWindow 来接收您的 ListView 消息,这样您就可以过滤消息。

实施

public class ListViewToolTipHelper : NativeWindow
{
    private ListView parentListView;
    private const int WM_NOTIFY = 78;
    private const int TTN_FIRST = -520;
    private const int TTN_NEEDTEXT = (TTN_FIRST - 10);
    public struct NMHDR
    {
        public IntPtr hwndFrom;
        public IntPtr idFrom;
        public Int32 code;
    }
    public bool TooltipEnabled { get; set; }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_NOTIFY && !TooltipEnabled)
        {
            var nmHdr = (NMHDR) m.GetLParam(typeof(NMHDR));
            if (nmHdr.code == TTN_NEEDTEXT)
                return;
        }

        base.WndProc(ref m);
    }
    public ListViewToolTipHelper(ListView listView)
    {
        this.parentListView = listView;
        this.AssignHandle(listView.Handle);
    }
}

用法

要禁用 ListView 的工具提示,您只需创建上面的实例 class:

ListViewToolTipHelper helper;
helper = new ListViewToolTipHelper(this.listView1);

再次启用工具提示:

helper.TooltipEnabled = true;

另一种解决方法

您可以使用此解决方法禁用 ListView 的工具提示,但副作用是表单中的所有其他工具提示也将被禁用。

ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(this.listView1, "dummy text");
toolTip.Active = false;