首页 > 代码库 > 初学c# -- 学习笔记(七) RichTextBox支持GIF

初学c# -- 学习笔记(七) RichTextBox支持GIF

园子里许明吉博客写的一篇,刚好用到这个,写的非常好。转过来了

不过在应用中也有一些问题,win10下不能中文输入,凑合着进行了修改,

下面是原来的代码:

private void button2_Click(object sender, EventArgs e)
        {
            IList<MemoryStream> _List = gifRichTextBox1.LoadSelectFile();

            for (int i = 0; i != _List.Count; i++)
            {
                File.WriteAllBytes(@"C:\Temp\A" + i.ToString() + ".gif", _List[0].ToArray());
            }
        }  

//添加一个GIF图形
        private void button3_Click(object sender, EventArgs e)
        {
            gifRichTextBox1.AddFile(@"C:\Temp\0.gif");
        }

//获取当前的RTF文字 你可以直接保存这个到数据库 或则通过SOCKET发送出去.
        string _Text = "";
        private void button1_Click(object sender, EventArgs e)
        {
            _Text = gifRichTextBox1.Rtf;


        }

//重新显示RTF内容

        private void button4_Click(object sender, EventArgs e)
        {
            gifRichTextBox1.Rtf = _Text;
        }

如果没有这个类..保存出的RTF数据..在其他RTF浏览的时候可能是个白色的矩形..

下面是全部的类

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

namespace Zgke.WindowFrom.Window.Controls.UserControls
{
    /// <summary>
    /// RichTextBox支持 GIF图形
    /// zgke@sina.com
    /// qq:116149
    /// </summary>
    public class GifRichTextBox : RichTextBox
    {      
        public GifRichTextBox()
        {
          
        }

        /// <summary>
        /// 重绘
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0xF)
            {
                foreach (Control _SubControl in base.Controls)
                {
                    _SubControl.Tag = "1";
                }

                GetRichTextObjRectangle();

                for (int i = 0; i != base.Controls.Count; i++)
                {
                    if (base.Controls[i].Tag.ToString() == "1")
                    {
                        base.Controls.RemoveAt(i);
                        i--;
                    }
                }
            }
            base.WndProc(ref m);
        }

        /// <summary>
        /// 添加一个文件资源到RTF数据
        /// </summary>
        /// <param name="p_FileFullPath">文件路径</param>    
        public void AddFile(string p_FileFullPath)
        {
            byte[] _FileBytes = File.ReadAllBytes(p_FileFullPath);
            Image _Image = Image.FromStream(new MemoryStream(_FileBytes));
            string _Guid = BitConverter.ToString(Guid.NewGuid().ToByteArray()).Replace("-", "");
            StringBuilder _RtfText = new StringBuilder(@"{\rtf1\ansi\ansicpg936\deff0\deflang1033\deflangfe2052{\fonttbl{\f0\fnil\fcharset134 \‘cb\‘ce\‘cc\‘e5;}}\uc1\pard\lang2052\f0\fs18{\object\objemb{\*\objclass Paint.Picture}");
            int _Width = _Image.Width * 15;
            int _Height = _Image.Height * 15;
            _RtfText.Append(@"\objw" + _Width.ToString() + @"\objh" + _Height.ToString());
            _RtfText.AppendLine(@"{\*\objdata");
            _RtfText.AppendLine(@"010500000200000007000000504272757368000000000000000000" + BitConverter.ToString(BitConverter.GetBytes(_FileBytes.Length + 20)).Replace("-", ""));
            _RtfText.Append("7A676B65" + _Guid); //标记            
            _RtfText.AppendLine(BitConverter.ToString(_FileBytes).Replace("-", ""));
            _RtfText.AppendLine(@"0105000000000000}{\result{\pict\wmetafile0}}}}");
            base.SelectedRtf = _RtfText.ToString();
        }

        /// <summary>
        /// 获取选择的文件
        /// </summary>
        /// <returns>文件列表</returns>
        public IList<MemoryStream> LoadSelectFile()
        {
            IList<MemoryStream> _FileList = new List<MemoryStream>();
            int _Index = base.SelectedRtf.IndexOf(@"{\*\objdata");
            if (_Index == -1) return _FileList;

            while (_Index != -1)
            {
                MemoryStream _File = new MemoryStream();
                _Index += 80;
                string _LengthText = base.SelectedRtf.Substring(_Index, 8);

                int _Length = BitConverter.ToInt32(new byte[] { Convert.ToByte(_LengthText.Substring(0, 2), 16), Convert.ToByte(_LengthText.Substring(2, 2), 16), Convert.ToByte(_LengthText.Substring(4, 2), 16), Convert.ToByte(_LengthText.Substring(6, 2), 16) }, 0);
                _Index += 10;

                string _Head = base.SelectedRtf.Substring(_Index, 8);              
                if (_Head.ToUpper() == "7A676B65")
                {
                    _Index += 40;
                    _Length -= 20;
                    int _EndIndex = base.SelectedRtf.IndexOf("01050000", _Index);                
                    int _ReadIndex = 0;
                    _FileList.Add(LoadMemoryStream(base.SelectedRtf.Substring(_Index, _EndIndex - _Index), ref _ReadIndex, _Length));
                    _Index = _EndIndex;
                }
                _Index = base.SelectedRtf.IndexOf(@"{\*\objdata", _Index);
            }
            return _FileList;
        }

        /// <summary>
        /// 获取图形或则改动PictureBox的位置
        /// </summary>
        /// <param name="p_Rtf"></param>
        private void PointFile(string p_Rtf, Point p_StarPoint, int p_Width, int p_Height)
        {
            int _Index = p_Rtf.IndexOf(@"{\*\objdata");
            if (_Index == -1) return;       
            _Index += 80;
            string _LengthText = p_Rtf.Substring(_Index, 8);

            int _Length = BitConverter.ToInt32(new byte[] { Convert.ToByte(_LengthText.Substring(0, 2), 16), Convert.ToByte(_LengthText.Substring(2, 2), 16), Convert.ToByte(_LengthText.Substring(4, 2), 16), Convert.ToByte(_LengthText.Substring(6, 2), 16) }, 0);
            _Index += 10;

            string _Head = p_Rtf.Substring(_Index, 8);
            if (_Head.ToUpper() != "7A676B65") return;   //如果不是标记出来的 就不生成PictureBox
            _Index += 8;

            string _Guid = p_Rtf.Substring(_Index, 32);

            Control _Controls = base.Controls[_Guid];
            if (_Controls == null)
            {
                PictureBox _PictureBox = new PictureBox();
                _PictureBox.Name = _Guid;
                _PictureBox.Tag = "0";
                _PictureBox.Location = p_StarPoint;
                _PictureBox.Size = new Size(p_Width, p_Height);

                _Index += 32;
                _Length -= 20;

                _PictureBox.Image = Image.FromStream(LoadMemoryStream(p_Rtf, ref _Index,_Length));

                base.Controls.Add(_PictureBox);
            }
            else
            {
                _Controls.Location = p_StarPoint;
                _Controls.Size = new Size(p_Width, p_Height);
                _Controls.Tag = "0";
            }
        }

        /// <summary>
        /// 根据RTF保存的内容获取内存流
        /// </summary>
        /// <param name="p_Text">RTF</param>
        /// <param name="p_Index">开始位置</param>
        /// <param name="p_Count">读取数量</param>
        /// <returns>内存流</returns>
        private MemoryStream LoadMemoryStream(string p_Text,ref int p_Index,int p_Count)
        {
            MemoryStream _File =new MemoryStream();
            char[] _Text = p_Text.ToCharArray();
            for (int i = 0; i != p_Count; i++)
            {
                if (_Text[p_Index] == ‘\r‘ && _Text[p_Index + 1] == ‘\n‘)
                {
                    i--;
                }
                else
                {
                    _File.WriteByte(Convert.ToByte(_Text[p_Index].ToString() + _Text[p_Index + 1].ToString(), 16));
                }
                p_Index += 2;
            }
            return _File;
        }
       
        /// <summary>
        /// 获取RICHTEXTBOX所有图形的位置
        /// </summary>
        /// <param name="p_RichTextBox">RICHTEXTBOX</param>
        /// <returns>位置信息</returns>
        private void GetRichTextObjRectangle()
        {
            RichTextBox _RichText = new RichTextBox();
            _RichText.Rtf = base.Rtf;
            int _Count = base.Text.Length;

            for (int i = 0; i != _Count; i++)
            {
                if (base.Text[i] == ‘ ‘)
                {
                    _RichText.Select(i, 1);

                    if (_RichText.SelectionType.ToString() == "Object")
                    {
                        Point _StarPoint = base.GetPositionFromCharIndex(i);

                        System.Text.RegularExpressions.Regex _RegexWidth = new System.Text.RegularExpressions.Regex(@"(?<=\\objw)[^\\]+");
                        System.Text.RegularExpressions.Regex _RegexHeight = new System.Text.RegularExpressions.Regex(@"(?<=\\objh)[^{]+");

                        int _Width = 0;
                        int _Height = 0;

                        if (int.TryParse(_RegexWidth.Match(_RichText.SelectedRtf).Value, out _Width) && int.TryParse(_RegexHeight.Match(_RichText.SelectedRtf).Value, out _Height))
                        {
                            _Width = _Width / 15;
                            _Height = _Height / 15;
                            PointFile(_RichText.SelectedRtf, _StarPoint, _Width, _Height);
                        }
                    }
                }
            }
            _RichText.Dispose();
        }      
    }
}

 

修改:

 if (m.Msg == 0xF)这句是重绘,改为

 if (m.Msg == 0x0007)

改完后问题又来了,不切换焦点图片不能删掉,又在程序里写按键事件:

先建立组件

gr = new GifRichTextBox();//建立

gr.Height = 200;            

gr.Width = 200;

gr.BackColor = Color.White;gr.KeyUp += new KeyEventHandler(rich_KeyUp);//加按键事件

.......

.......

//判断是否delete键或backspace,失去焦点再获得

private void rich_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Delete)|| (e.KeyCode == Keys.Back))
            {
                this.Focus();
                gr.Focus();
            }
        }

测试是过了,就是觉得还是麻烦。有没有更好的法子,告诉我一下。

在消息里找来找去,就焦点好用点,所有消息列表:

public const int WM_NULL = 0x0000; //   
        public const int WM_CREATE = 0x0001; //应用程序创建一个窗口   
        public const int WM_DESTROY = 0x0002; //一个窗口被销毁   
        public const int WM_MOVE = 0x0003; //移动一个窗口   
        public const int WM_SIZE = 0x0005; //改变一个窗口的大小   
        public const int WM_ACTIVATE = 0x0006; //一个窗口被激活或失去激活状态;   
        public const int WM_SETFOCUS = 0x0007; //获得焦点后   
        public const int WM_KILLFOCUS = 0x0008; //失去焦点   
        public const int WM_ENABLE = 0x000A; //改变enable状态   
        public const int WM_SETREDRAW = 0x000B; //设置窗口是否能重画   
        public const int WM_SETTEXT = 0x000C; //应用程序发送此消息来设置一个窗口的文本   
        public const int WM_GETTEXT = 0x000D; //应用程序发送此消息来复制对应窗口的文本到缓冲区   
        public const int WM_GETTEXTLENGTH = 0x000E; //得到与一个窗口有关的文本的长度(不包含空字符)   
        public const int WM_PAINT = 0x000F; //要求一个窗口重画自己   
        public const int WM_CLOSE = 0x0010; //当一个窗口或应用程序要关闭时发送一个信号   
        public const int WM_QUERYENDSESSION = 0x0011; //当用户选择结束对话框或程序自己调用ExitWindows函数   
        public const int WM_QUIT = 0x0012; //用来结束程序运行或当程序调用postquitmessage函数   
        public const int WM_QUERYOPEN = 0x0013; //当用户窗口恢复以前的大小位置时,把此消息发送给某个图标   
        public const int WM_ERASEBKGND = 0x0014; //当窗口背景必须被擦除时(例在窗口改变大小时)   
        public const int WM_SYSCOLORCHANGE = 0x0015; //当系统颜色改变时,发送此消息给所有顶级窗口   
        public const int WM_ENDSESSION = 0x0016; // 当系统进程发出WM_QUERYENDSESSION消息后,此消息发送给应用程序,通知它对话是否结束   
        public const int WM_SYSTEMERROR = 0x0017; //   
        public const int WM_SHOWWINDOW = 0x0018; //当隐藏或显示窗口是发送此消息给这个窗口   
        public const int WM_ACTIVATEAPP = 0x001C; //发此消息给应用程序哪个窗口是激活的,哪个是非激活的;   
        public const int WM_FONTCHANGE = 0x001D; //当系统的字体资源库变化时发送此消息给所有顶级窗口   
        public const int WM_TIMECHANGE = 0x001E; //当系统的时间变化时发送此消息给所有顶级窗口   
        public const int WM_CANCELMODE = 0x001F; //发送此消息来取消某种正在进行的摸态(操作)   
        public const int WM_SETCURSOR = 0x0020; //如果鼠标引起光标在某个窗口中移动且鼠标输入没有被捕获时,就发消息给某个窗口  
        public const int WM_MOUSEACTIVATE = 0x0021; //当光标在某个非激活的窗口中而用户正按着鼠标的某个键发送此消息给当前窗口   
        public const int WM_CHILDACTIVATE = 0x0022; //发送此消息给MDI子窗口当用户点击此窗口的标题栏,或当窗口被激活,移动,改变大小   
        public const int WM_QUEUESYNC = 0x0023; //此消息由基于计算机的训练程序发送,通过WH_JOURNALPALYBACK的hook程序分离出用户输入消息   
        public const int WM_GETMINMAXINFO = 0x0024; //此消息发送给窗口当它将要改变大小或位置;   
        public const int WM_PAINTICON = 0x0026; //发送给最小化窗口当它图标将要被重画   
        public const int WM_ICONERASEBKGND = 0x0027; //此消息发送给某个最小化窗口,仅当它在画图标前它的背景必须被重画   
        public const int WM_NEXTDLGCTL = 0x0028; //发送此消息给一个对话框程序去更改焦点位置   
        public const int WM_SPOOLERSTATUS = 0x002A; //每当打印管理列队增加或减少一条作业时发出此消息   
        public const int WM_DRAWITEM = 0x002B; //当button,combobox,listbox,menu的可视外观改变时发送此消息给这些空件的所有者   
        public const int WM_MEASUREITEM = 0x002C; //当button, combo box, list box, list view control, or menu item 被创建时发送此消息给控件的所有者   
        public const int WM_DELETEITEM = 0x002D; // 当the list box 或combo box 被销毁或当某些项被删除通过LB_DELETESTRING, LB_RESETCONTENT, CB_DELETESTRING, or CB_RESETCONTENT 消息   
        public const int WM_VKEYTOITEM = 0x002E; //此消息有一个LBS_WANTKEYBOARDINPUT风格的发出给它的所有者来响应WM_KEYDOWN消息   
        public const int WM_CHARTOITEM = 0x002F; //此消息由一个LBS_WANTKEYBOARDINPUT风格的列表框发送给他的所有者来响应WM_CHAR消息   
        public const int WM_SETFONT = 0x0030; //当绘制文本时程序发送此消息得到控件要用的颜色   
        public const int WM_GETFONT = 0x0031; //应用程序发送此消息得到当前控件绘制文本的字体   
        public const int WM_SETHOTKEY = 0x0032; //应用程序发送此消息让一个窗口与一个热键相关连   
        public const int WM_GETHOTKEY = 0x0033; //应用程序发送此消息来判断热键与某个窗口是否有关联   
        public const int WM_QUERYDRAGICON = 0x0037; //此消息发送给最小化窗口,当此窗口将要被拖放而它的类中没有定义图标,应用程序能   
        //返回一个图标或光标的句柄,当用户拖放图标时系统显示这个图标或光标   
        public const int WM_COMPAREITEM = 0x0039; //发送此消息来判定combobox或listbox新增加的项的相对位置   
        public const int WM_GETOBJECT = 0x003D; //WM_COMPACTING = 0x0041; //显示内存已经很少了   
        public const int WM_WINDOWPOSCHANGING = 0x0046; //发送此消息给那个窗口的大小和位置将要被改变时,来调用setwindowpos函数或其它窗口管理函数   
        public const int WM_WINDOWPOSCHANGED = 0x0047; //发送此消息给那个窗口的大小和位置已经被改变时,来调用setwindowpos函数或其它窗口管理函数   
        public const int WM_POWER = 0x0048; //(适用于16位的windows)当系统将要进入暂停状态时发送此消息   
        public const int WM_COPYDATA = http://www.mamicode.com/0x004A; //当一个应用程序传递数据给另一个应用程序时发送此消息   >

 

初学c# -- 学习笔记(七) RichTextBox支持GIF