在系统自带的RichTextBox中是无法给它设置背景图片,但是我们在某些场合可能需要给RichTextBox设置背景图片。那么怎么实现这一想法呢?经过研究发现通过其它巧妙的途径可以给RichTextBox设置背景图片。首先将RichTextBox这个控件加以改写。具体改写的代码如下:

 public partial class richTextBoxEx : RichTextBox
    {
        public richTextBoxEx()
        {
            InitializeComponent();
            base.ScrollBars = RichTextBoxScrollBars.None;
          
        }

        public richTextBoxEx(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
          
        }
        //这个要加上
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20;
                return cp;

            }
        }

    }

CreateParams 中的信息可用于传递有关控件的初始状态和外观的信息。多数 Control 派生控件重写 CreateParams 属性以传递适当的值或在 CreateParams 中包含附加信息。

关于CreateParams的详细介绍请查看MSDN:http://msdn.microsoft.com/zh-cn/library/b0c6ds4f%28v=VS.85%29.aspx

改写完毕后首先放置一个Panel到窗体上面,同时放置一个和Panel相同大小的richTextBoxEx到Panel上,将需要给richTextBox设置的背景图片设置给panel,将panel的背景色设置为透明即可。但是这样虽然给richTextBox设置了背景,但是在显示时会有比较明显的闪动。因此需要对Panel控件加以改良,改写的代码如下:

public class PanelEx:Panel
    {
        public PanelEx()
        {
          
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            return;
        }

        protected override void OnPaint(PaintEventArgs e)
        {

            this.DoubleBuffered = true;
            if (this.BackgroundImage != null)
            {
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                e.Graphics.DrawImage(this.BackgroundImage, new System.Drawing.Rectangle(00this.Width, this.Height),
                00this.BackgroundImage.Width, this.BackgroundImage.Height,
                System.Drawing.GraphicsUnit.Pixel);
            }
            //base.OnPaint(e);

        }

}

使用这个panelEx虽然没有能彻底的消除闪烁的效果,但是已经好很多了,没有刚才那么明显了。本人能力有限,只能做到这一步了,

如果那位大侠有更好的解决方案,请赐教。