Label:根据文字自动调整大小 并 添加tooltip提示

8 篇文章 0 订阅

http://www.cnblogs.com/nicch/archive/2008/11/05/1326754.html

tooltip有时不显示:

添加MouseEnter,MouseLeave事件,
在MouseEnter里加this.toolTip1.SetToolTip(控件, 内容);//显示ToolTip
在MouseLeave里加this.toolTip1.RemoveAll();//清除ToolTip

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


namespace monitor
{
    internal class LabelEx : System.Windows.Forms.Label
    {
        public LabelEx()
            : base()
        {
            //关闭AutoSize
            //this.AutoSize = false;
            //捕捉事件
            toolTip = new ToolTip();
            toolTip.ShowAlways = true;
            this.TextChanged += new EventHandler(LabelEx_TextChanged);
            this.MouseLeave+=new EventHandler(LabelEx_MouseLeave);
            this.MouseEnter+=new EventHandler(LabelEx_MouseEnter);
            this.SizeChanged += new EventHandler(LabelEx_SizeChanged);
        }
        //记录原始的宽度
        int _oldw;
        ToolTip toolTip;
        void LabelEx_SizeChanged(object sender, EventArgs e)
        {
            //如果宽度没变,那就返回
            if (this.Width == _oldw) return;


            //重新计算高度
            LabelEx_TextChanged(null, null);


            //记录
            _oldw = this.Width;
        }


        /// <summary>
        /// 重写AutoSize属性,防止AutoSize再被打开
        /// </summary>
        public override bool AutoSize
        {
            get
            {
                return false;
            }
        }


        /// <summary>
        /// 是否自动调整父控件
        /// </summary>
        public bool AutoResizeParent { get; set; }


        void LabelEx_TextChanged(object sender, EventArgs e)
        {
            //记录下当前的高度
            int oh = this.Height;


            //文字变化了,那就改变一下当前的大小
            System.Drawing.Size ps = GetPreferredSize(this.Size);


            //这里构造一个新的Size对象,目的是使用原始的宽度。原因嘛,见上面
            this.Size = new System.Drawing.Size(this.Width, ps.Height);


            if (this.Parent != null && AutoResizeParent)
            {
                //调整容器大小
                this.Parent.Size = new System.Drawing.Size(this.Parent.Width, ps.Height - oh + this.Parent.Height);
            }
            toolTip.SetToolTip(this, this.Text);
        }


        void LabelEx_MouseLeave(object sender, EventArgs e)
        {
            this.toolTip.RemoveAll();
        }


        void LabelEx_MouseEnter(object sender, EventArgs e)
        {
            toolTip.SetToolTip(this, this.Text);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值