//richTextBox1.DetectUrls = false; // 自动识别连接关闭
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public class CHARFORMAT2A
{
public int cbSize;
public int dwMask;
public int dwEffects;
public int yHeight;
public int yOffset;
public int crTextColor;
public byte bCharSet;
public byte bPitchAndFamily;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
public byte[] szFaceName = new byte[0x20];
public short wWeight;
public short sSpacing;
public int crBackColor;
public int lcid;
public int dwReserved;
public short sStyle;
public short wKerning;
public byte bUnderlineType;
public byte bAnimation;
public byte bRevAuthor;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] CHARFORMAT2A lParam);
public const int CFE_LINK= 0x20;
public const int CFM_LINK = 0x20;
public const int EM_SETCHARFORMAT = 0x444;
public const int SCF_SELECTION = 1;
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;
}
private void button1_Click(object sender, EventArgs e)
{
string insertText = @"床上等你";
string insertLink = @"#http://www.youkuaiyun.com";
string insertRtf = @"{/rtf1 " +
TextToRtf(insertText) + @"/v " + TextToRtf(insertLink) + @"/v0}";
int start = richTextBox1.SelectionStart;
richTextBox1.SelectedRtf = insertRtf;
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = insertText.Length + insertLink.Length;
CHARFORMAT2A vCharFormat2a = new CHARFORMAT2A();
vCharFormat2a.cbSize = Marshal.SizeOf(typeof(CHARFORMAT2A));
vCharFormat2a.dwMask = CFM_LINK;
vCharFormat2a.dwEffects = CFE_LINK;
SendMessage(richTextBox1.Handle, EM_SETCHARFORMAT, SCF_SELECTION,
vCharFormat2a);
}
private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
MessageBox.Show(e.LinkText.Substring(e.LinkText.IndexOf('#')));
}
本文介绍如何使用C#实现富文本框中带有链接的文本插入,并通过CHARFORMAT2A结构体来设置选中文本的链接属性。通过具体的代码示例展示了如何将普通文本转换为RTF格式并插入到富文本框中。
474

被折叠的 条评论
为什么被折叠?



