附件:http://files.cnblogs.com/xe2011/richTextBox_InsertTable.rar

richTextBox插入表格-LMLPHP

插入表格

       /// <summary>
/// 插入表格
/// </summary>
/// <param name="richTextBox"></param>
/// <param name="col">行</param>
/// <param name="row">列</param>
/// <param name="AutoSize">=TRUE:自动设置每个单元格的大小</param>
private void InsertTable(RichTextBox richTextBox,int col, int row,bool AutoSize)
{
StringBuilder rtf = new StringBuilder();
rtf.Append(@"{\rtf1 "); //int cellWidth = 1000;//col.1 width =1000
int cellWidth = ; if (AutoSize)
//滚动条出现时 (richTextBox.ClientSize.Width - 滚动条的宽 /列的个数)*15
cellWidth = (richTextBox.ClientSize.Width / row) * ; //15 当ROW值越大 结果差距越大 Text = cellWidth.ToString() ;
for (int i = ; i < col; i++)
{
rtf.Append(@"\trowd");
for (int j = ; j <= row; j++)
rtf.Append(@"\cellx" + (j * cellWidth).ToString());
rtf.Append(@"\intbl \cell \row"); //create row
}
rtf.Append(@"\pard");
rtf.Append(@"}");
richTextBox.SelectedRtf = rtf.ToString();
}

扩展的richTextBox

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms; namespace richTextBoxTableClass
{
public class CustomRichTextBox : RichTextBox
{ ///支持表格正确粘贴
// P/Invoke declarations
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(string path); private static IntPtr moduleHandle; protected override CreateParams CreateParams
{
get
{
if (moduleHandle == IntPtr.Zero)
{
moduleHandle = LoadLibrary("msftedit.dll");
if ((long)moduleHandle < 0x20)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not load Msftedit.dll");
}
} CreateParams createParams = base.CreateParams;
createParams.ClassName = "RichEdit50W";
if (this.Multiline)
{
if (((this.ScrollBars & RichTextBoxScrollBars.Horizontal) != RichTextBoxScrollBars.None) &&!base.WordWrap)
{
createParams.Style |= 0x100000;
if ((this.ScrollBars & ((RichTextBoxScrollBars)0x10)) != RichTextBoxScrollBars.None)
{
createParams.Style |= 0x2000;
}
}
if ((this.ScrollBars & RichTextBoxScrollBars.Vertical) != RichTextBoxScrollBars.None)
{
createParams.Style |= 0x200000;
if ((this.ScrollBars & ((RichTextBoxScrollBars)0x10)) != RichTextBoxScrollBars.None)
{
createParams.Style |= 0x2000;
}
}
}
if ((BorderStyle.FixedSingle == base.BorderStyle) && ((createParams.Style & 0x800000) != ))
{
createParams.Style &= -;
createParams.ExStyle |= 0x200;
}
return createParams;
}
} }
}

CustomRichTextBox.CS

调用

        private void button1_Click(object sender, EventArgs e)
{
InsertTable(richTextBox1, , , false);
InsertTable(richTextBox51,, , false);
}
05-08 15:24