Winform 中实现背景颜色可以设置成半透明的RichTextBox

背景

上次制作的串口工具又出问题了,窗口的要求用图片做背景,但是RichTextBox无法将背景颜色设置为Transparent,一个白白的框框给图片遮了一大半,丑的辣眼睛。

在网站上找资料,发现有一个很简洁的方法:

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x00000020; // 开启 WS_EX_TRANSPARENT,使控件支持透明  
        return cp;
    }
} 

这样的做法,固然可以实现控件背景的完全透明,但无法满足半透明的要求,所以用了一个简单粗暴的方式:
- 1、创建一个RichTextBox派生类- CustomControl1,override 它的 CreateParams属性
- 2、构造中SetStyle(ControlStyles.SupportsTransparentBackColor, true);//使允许透明背景透明
- 3、base.BackColor = Color.Transparent; //背景设透明色
- 4、创建一个自定义控件 - UserControl1,将base.BackColor设置为Transparent
- 5、override 自定义控件的BackColor,屏蔽其Set功能
- 6、override 自定义控件的OnPaint,在其中绘制透明颜色
- 7、在自定义控件里添加上面创建的RichTextBox派生类
- 8、在自定义控件中“透传”CustomControl1的各个必须的属性和方法

具体实现

CustomControl1:

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

namespace WallSwipeTestTool2.MyControl
{
    public partial class CustomControl1 : RichTextBox
    {
        public CustomControl1()
        {          
            ControlStyles styles = ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer;
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);//使允许透明背景透明  
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//使用双缓存
            base.CreateControl();  
            InitializeComponent();
            base.BackColor = Color.Transparent;  //背景设透明色
        }

        //在文本改变时主动引起Paint,否则会留下光标的痕迹
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            this.Refresh();
        }

        //在拖动滑动条时重绘,否则整个界面会"糊掉"()
        protected override void OnVScroll(EventArgs e)
        {
            base.OnVScroll(e);
            this.Refresh();
        }
        //在拖动滑动条时重绘,否则整个界面会"糊掉"
        protected override void OnHScroll(EventArgs e)
        {
            base.OnHScroll(e);
            this.Refresh();
        }

        //让背景透明
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x00000020; // 开启 WS_EX_TRANSPARENT,使控件支持透明  
                return cp;
            }
        }  
    }
}

UserControl1:

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

namespace WallSwipeTestTool2.MyControl
{
    public partial class UserControl1 : UserControl
    {
        private int _alpha = 80;//设置透明度  
        private bool _isTransparent = true;//是否透明 
        private Color _backColor = Color.White;

        public UserControl1()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            InitializeComponent();
        }

        /// 摘要:
        ///     向文本框的当前文本追加文本。
        ///
        /// 参数:
        ///   text:
        ///     要向文本框的当前内容追加的文本。
        public void AppendText(string text)
        {
            this.customControl11.AppendText(text);
        }

        //
        // 摘要:
        //     将控件的内容滚动到当前插入符号位置。
        public void ScrollToCaret()
        {
            this.customControl11.ScrollToCaret();
        }

        //
        // 摘要:
        //     从文本框控件中清除所有文本。
        public void Clear()
        {
            this.customControl11.Clear();
        }

        #region 属性

        public int SelectionStart
        {
            get { return this.customControl11.SelectionStart; }
            set { this.customControl11.SelectionStart = value; }
        }

        public string SelectedText
        {
            get { return this.customControl11.SelectedText; }
            set { this.customControl11.SelectedText = value; }
        }

        public Color SelectionColor
        {
            get { return this.customControl11.SelectionColor; }
            set { this.customControl11.SelectionColor = value; }
        }
        [Browsable(true), Category("XX控件"), Description("设置获取前景颜色"), DefaultValue(typeof(Color), "Black")]
        public new  Color ForeColor
        {
            get { return this.customControl11.ForeColor; }
            set { this.customControl11.ForeColor = value; }
        }

        [Browsable(true), Category("XX控件"), Description("控制是否编辑文本框中的文本"), DefaultValue(typeof(Font), "宋体, 9pt")]
        public new Font Font
        {
            get { return this.customControl11.Font; }
            set { this.customControl11.Font = value; }
        }

        [Browsable(true), Category("XX控件"), Description("控制是否编辑文本框中的文本"), DefaultValue(false)]
        public bool ReadOnly
        {
            get { return this.customControl11.ReadOnly; }
            set { this.customControl11.ReadOnly = value; }
        }

        [Browsable(false),Category("XX控件"), Description("设置或获取选择的背景颜色"), DefaultValue("")]
        public Color SelectionBackColor
        {
            get { return this.customControl11.SelectionBackColor; }
            set { this.customControl11.SelectionBackColor = value; }
        }

        [Browsable(true), Category("XX控件"), Description("设置或获取显示的文本"), DefaultValue("")]
        public new string Text
        {
            get { return this.customControl11.Text; }
            set { this.customControl11.Text = value; }
        }

        [Browsable(true), Category("XX控件"), Description("设置或获取透明度"), DefaultValue(80)]
        public int Alpha
        {
            get { return _alpha; }
            set { _alpha = value; }
        }

        [Browsable(true), Category("XX控件"), Description("是否使用透明,默认为True"), DefaultValue(true)]
        public bool IsTransparent
        {
            get { return _isTransparent; }
            set { _isTransparent = value; }
        }

        [Browsable(true), Category("XX控件"), Description("设置获取透明背景颜色"), DefaultValue(typeof(Color), "Transparent")]
        public Color AlphaBackColor
        {
            get
            {
                return this._backColor;;
            }
            set
            {
                this._backColor = value;
                base.BackColor = Color.Transparent;
            }  
        }

        [Browsable(false), Category("XX控件"), Description("设置获取背景颜色"), DefaultValue(typeof(Color), "Transparent")]
        public override Color BackColor
        {
            get
            {
                return base.BackColor;
            }
        }
        #endregion

        #region Overrides


        protected override void OnPaint(PaintEventArgs e)
        {
            Bitmap bmp = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, e.Graphics);
            Graphics g = Graphics.FromImage(bmp);
            Pen labelBorderPen;
            SolidBrush labelBackColorBrush;
            if (_isTransparent)
            {
                Color cl = Color.FromArgb(_alpha, this._backColor);
                labelBorderPen = new Pen(Color.Black, 2);
                labelBackColorBrush = new SolidBrush(cl);
            }
            else
            {
                labelBorderPen = new Pen(this._backColor, 0);
                labelBackColorBrush = new SolidBrush(_backColor);
            }

            g.DrawRectangle(labelBorderPen, 0, 0, this.Width, this.Height);
            g.FillRectangle(labelBackColorBrush, 0, 0, this.Width, this.Height);

            base.OnPaint(e);
            e.Graphics.DrawImage(bmp, 0, 0);
            bmp.Dispose();
        }

        #endregion

        private void customControl11_TextChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }


        private void customControl11_Scroll(object sender, EventArgs e)
        {
            this.Refresh();
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页