日期:2014-05-17  浏览次数:20783 次

代码分享,WinForm中LinkLabel实现关键字高亮
本帖最后由 caozhy 于 2013-09-12 04:10:50 编辑
效果:


使用说明:

IgnoreCase 是否匹配大小写,默认false,严格匹配大小写

Keyword 关键字

KeywordColor 关键字的颜色,默认红色

BUG列表:

部分颜色属性不工作,比如访问后颜色,自定义背景色等等

不支持多行文本

代码:

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

namespace WindowsFormsApplication1
{
    class SuperLinkLabel : LinkLabel
    {
        public bool IgnoreCase { get; set; }

        private string keyWord = "";
        public string Keyword
        {
            get { return keyWord; }
            set { keyWord = value; this.Invalidate(); }
        }

        public Color KeywordColor { get; set; }

        public SuperLinkLabel()
        {
            Keyword = "";
            KeywordColor = Color.Red;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(SystemColors.Control), e.ClipRectangle);

            StringFormat stringFormat = new StringFormat();
            stringFormat.SetMeasurableCharacterRanges(GetRanges());
            stringFormat.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
            Region[] regions = e.Graphics.MeasureCharacterRanges(Text, Font, new RectangleF(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width + 200, e.ClipRectangle.Height), stringFormat);