richtextbox中插入文件路径链接时出错的处理

本文在http://blog.csdn.net/greystar/archive/2008/03/13/2175958.aspx 此基础上进行了扩展.

当在richtextbox中我们插入一个链接时,如果链接是文件路径时(如C:/aa/bb.doc)时,/符号会丢失.这样如果我们想在些连接上单击时,获取的数据就不正确. 

 public void InsertLink(string text, string hyperlink, int position)
        {
            if (position < 0 || position > this.Text.Length)
                throw new ArgumentOutOfRangeException("position");

            this.SelectionStart = position;
           // this.SelectedRtf = @"{/rtf1/ansi " + text + @"/v #" + hyperlink + @"/v0}"; //会出现中文乱码情况,            this.SelectedRtf = @"{/rtf1/ansicpg936 " + TextToRtf(text) + @"/v #" + hyperlink + @"/v0}";
            this.Select(position, text.Length + hyperlink.Length + 1);
            this.SetSelectionLink(true);
            this.Select(position + text.Length + hyperlink.Length + 1, 0);
        }
        //路径处理时用
        public string TextToRtf(string AText)
        {
            string vReturn = "";
            foreach (char vChar in AText)
            {
                switch (vChar)
                {
                    case '//':
                        vReturn += @"//";
                        break;
                    case '{':
                        vReturn += @"/{";
                        break;
                    case '}':
                        vReturn += @"/}";
                        break;
                    default:
                        if (vChar > (char)127)
                            vReturn += @"/u" + ((int)vChar).ToString() + "?";
                        else vReturn += vChar;
                        break;
                }
            }
            return vReturn;
        }
此文上和http://blog.csdn.net/greystar/archive/2008/03/13/2175958.aspx差不多,只是多了一个转换

你可能感兴趣的:(richtextbox中插入文件路径链接时出错的处理)