zoukankan      html  css  js  c++  java
  • C# richTextBox编辑器

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

     完整的转到这里 http://www.cnblogs.com/xe2011/p/3449333.html

    主要的类

      1 using System;
      2 //using System.Collections.Generic;
      3 //using System.Linq;
      4 using System.Text;
      5 using System.Drawing;
      6 //using System.Windows.Forms;
      7 using System.Runtime.InteropServices;
      8 using System.Drawing.Printing;
      9 using System.ComponentModel;
     10 using System.IO;
     11 using RichTextBoxCtrl;
     12 using richTextBoxTableClass;
     13  
     14 #region 添加引用 说明
     15 //右键选中 引用 添加引用
     16 //在“添加引用”对话框中,
     17 //双击“System.Drawing.dll”和
     18 //“System.Windows.Forms.dll”,然后单击“确定”。
     19 #endregion
     20 
     21 
     22 namespace System.Windows.Forms
     23 {
     24     public class RichTextBoxCtrl : RichTextBox
     25     {
     26 
     27         #region RichTextBox初始化属性
     28         /// <summary>
     29         /// richTextBox1 = this;
     30         /// </summary>
     31         private System.Windows.Forms.RichTextBox richTextBox1;
     32 
     33         public RichTextBoxCtrl()
     34         {
     35             richTextBox1 = this;
     36             AllowDrop = true;
     37             EnableAutoDragDrop = true;
     38             AcceptsTab = true;
     39             HideSelection = false;
     40             ScrollBars = RichTextBoxScrollBars.Vertical;
     41             InitialRichTextBoxCtrl();
     42             
     43         }
     44         #endregion
     45 
     46         #region RichTextBox 新建 打开 和 保存 文件对话框
     47 
     48         private string fileName = "未命名.rtf";
     49         private string absFileName = "";
     50 
     51         //文件名 返回 如 abc.rtf  
     52         public string FileName
     53         {
     54             get{
     55                 return fileName;
     56             }
     57         }
     58 
     59         //格式 C:windowsabc.rtf
     60         public string AbsFileName
     61         {
     62             get {
     63                 return absFileName;
     64             }
     65         }
     66         
     67 
     68         /// <summary>
     69         /// 判断文件是否保存了
     70         /// </summary>
     71         private void CheckFileSave()
     72         {
     73             if (this.Modified)
     74             {
     75                 string msg = "";
     76                 if (File.Exists(absFileName))
     77                     msg = "文档已修改是否保存:" + fileName;
     78                 else
     79                     msg = "文档已修改是否保存";
     80 
     81                 DialogResult Result = MessageBox.Show(msg, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     82                 if (Result == DialogResult.Yes)
     83                 {
     84                     if (File.Exists(absFileName))
     85                         richTextBox1.SaveFile(absFileName);
     86                     else
     87                         this.ShowSaveFileDlg();
     88                 }
     89             }
     90         }
     91 
     92         /// <summary>
     93         /// 新空的文档
     94         /// </summary>
     95         public void NewDocument()
     96         {
     97             CheckFileSave();
     98 
     99             richTextBox1.Text = "";
    100             richTextBox1.Modified = false;
    101 
    102             absFileName = "";
    103             fileName = "";
    104         }
    105 
    106         /// <summary>
    107         /// 打开文件
    108         /// </summary>
    109         public void ShowOpenFileDlg()
    110         {
    111             CheckFileSave();
    112 
    113             OpenFileDialog openFileDialog1 = new OpenFileDialog();
    114             openFileDialog1.DefaultExt = ".rtf";
    115             openFileDialog1.Filter = "RTF 文档(*.rtf)|*.rtf|所有文件(*.*)|*.*";
    116             if (openFileDialog1.ShowDialog() == DialogResult.OK)
    117             {
    118                 LoadFile(openFileDialog1.FileName);
    119                 Modified = false;
    120 
    121                 absFileName = openFileDialog1.FileName;
    122                 fileName = Path.GetFileName(absFileName);
    123             }
    124         }
    125 
    126         //另存文件
    127         public void ShowSaveFileDlg()
    128         {
    129             SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    130             saveFileDialog1.DefaultExt = ".rtf";
    131             saveFileDialog1.Filter = "RTF 文档(*.rtf)|*.rtf|所有文件(*.*)|*.*";
    132             saveFileDialog1.FileName = FileName;
    133             if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    134             {
    135                 SaveFile(saveFileDialog1.FileName);
    136                 Modified = false;
    137              
    138                 absFileName = saveFileDialog1.FileName;
    139                 fileName = Path.GetFileName(absFileName);
    140             }
    141         }
    142      
    143         #endregion
    144 
    145         #region 把RTF文件保存为纯文本
    146        
    147         /// <summary>
    148         /// 把RTF文件保存为纯文本
    149         /// 只保存字符 转换后文本不包括RTF中的图片信息
    150         /// </summary>
    151         /// <param name="TextFileName">"C:UsersAdminDesktopCurRoleBase.txt"</param>
    152         public void SaveToTextFile(string TextFileName)
    153         {
    154             this.SaveFile(TextFileName, RichTextBoxStreamType.TextTextOleObjs);
    155         }
    156         #endregion
    157 
    158         #region 设置为只读模式
    159 
    160         [DllImport("user32.dll")]
    161         static extern bool HideCaret(IntPtr hWnd);
    162        
    163        
    164         /// <summary>
    165         /// HideCaret 
    166         /// </summary>
    167         /// <param name="m"></param>
    168         protected override void WndProc(ref Message m)
    169         {
    170             base.WndProc(ref m);
    171             if (ReadOnly)
    172                 HideCaret(Handle);
    173         }
    174         #endregion
    175 
    176         #region 设置 和 获得光标所在的行号和列号
    177         ///要在本类中初始化 richTextBox1 = this;
    178         private int EM_LINEINDEX = 0x00BB;
    179         private int EM_LINEFROMCHAR = 0x00C9;
    180 
    181         [DllImport("user32.dll", EntryPoint = "SendMessage")]
    182         public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
    183 
    184         
    185         /// <summary>
    186         /// 获得光标所在的行号和列号
    187         /// </summary>
    188         /// <param name="editControl"></param>
    189         /// <returns>p.X = 行号 p.Y =列号</returns>
    190         public Point GetCaretPosition()
    191         {
    192             int charIndex = (int)SendMessage(richTextBox1.Handle, EM_LINEINDEX, -1, 0);
    193             int lineIndex = (int)SendMessage(richTextBox1.Handle, EM_LINEFROMCHAR, charIndex, 0);
    194             Point pt=new Point();
    195             pt.X = richTextBox1.SelectionStart - charIndex +1;//Line
    196             pt.Y = lineIndex +1;//Column
    197             return pt;
    198         }
    199 
    200 
    201         /// <summary>
    202         /// 转到行
    203         /// </summary>
    204         /// <param name="Line">行号</param>
    205         public void jumpLine(int Line)
    206         {
    207             richTextBox1.SelectionStart = SendMessage(richTextBox1.Handle, EM_LINEINDEX, Line - 1, 0);
    208             richTextBox1.SelectionLength = 0;
    209             richTextBox1.ScrollToCaret();
    210         }
    211 
    212 
    213         /// <summary>
    214         /// 有问题 同时设置行号和列号就出现问题了
    215         /// </summary>
    216         /// <param name="Column"></param>
    217         public void jumpColumn(int Column)
    218         {
    219             int Line = Column;
    220 
    221             int charIndex = (int)SendMessage(richTextBox1.Handle, EM_LINEINDEX, Line - 1, 0);
    222             int lineIndex = charIndex + (int)SendMessage(richTextBox1.Handle, EM_LINEFROMCHAR, charIndex, 0);
    223 
    224             richTextBox1.SelectionStart = lineIndex;
    225         }
    226         #endregion
    227 
    228         #region RichTextBox 字体样式
    229         //格式刷
    230 
    231 
    232         /// richTextBox1 = this;
    233         
    234         /// <summary>
    235         /// 粗体
    236         /// </summary>
    237         public void ToggleBold()
    238         {
    239             if (richTextBox1.SelectionFont == null)
    240                 richTextBox1.SelectionFont = richTextBox1.Font;
    241 
    242             FontStyle style = richTextBox1.SelectionFont.Style;
    243 
    244             if (richTextBox1.SelectionFont.Bold)
    245 
    246                 style &= ~FontStyle.Bold;//恢复正常
    247             else
    248                 style |= FontStyle.Bold;
    249 
    250             richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, style);
    251         }
    252 
    253         /// <summary>
    254         /// 斜体
    255         /// </summary>
    256         public void ToggleItalic()
    257         {
    258             if (richTextBox1.SelectionFont == null)
    259                 richTextBox1.SelectionFont = richTextBox1.Font;
    260 
    261             FontStyle style = richTextBox1.SelectionFont.Style;
    262 
    263             if (richTextBox1.SelectionFont.Italic)
    264                 style &= ~FontStyle.Italic;//恢复正常
    265             else
    266                 style |= FontStyle.Italic;
    267 
    268             richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, style);
    269         }
    270 
    271         /// <summary>
    272         /// 下划线
    273         /// </summary>
    274         public void ToggleUnderLine()
    275         {
    276             if (richTextBox1.SelectionFont == null)
    277                 richTextBox1.SelectionFont = richTextBox1.Font;
    278 
    279             FontStyle style = richTextBox1.SelectionFont.Style;
    280 
    281             if (richTextBox1.SelectionFont.Underline)
    282                 style &= ~FontStyle.Underline;//恢复正常
    283             else
    284                 style |= FontStyle.Underline;
    285 
    286             richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, style);
    287         }
    288 
    289         /// <summary>
    290         /// 删除线
    291         /// </summary>
    292         public void ToggleStrikeout()
    293         {
    294             if (richTextBox1.SelectionFont == null)
    295                 richTextBox1.SelectionFont = richTextBox1.Font;
    296 
    297             FontStyle style = richTextBox1.SelectionFont.Style;
    298 
    299             if (richTextBox1.SelectionFont.Strikeout)
    300                 style &= ~FontStyle.Strikeout;//恢复正常
    301             else
    302                 style |= FontStyle.Strikeout;
    303             richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, style);
    304         }
    305        
    306 
    307         //标题1 ,标题2....
    308         public void SetFontFormat(int index)
    309         {
    310              richTextBoxFontFormatClass FontFormat1 = new richTextBoxFontFormatClass();
    311              FontFormat1.richTextBox = this;
    312              FontFormat1.SetFontFormat(index);
    313         }
    314 
    315         public string GetFontFormat()
    316         {
    317             richTextBoxFontFormatClass FontFormat1 = new richTextBoxFontFormatClass();
    318             FontFormat1.richTextBox = this;
    319             return FontFormat1.GetFontFormat();
    320         }
    321 
    322         /// <summary>
    323         /// 设置上标
    324         /// </summary>
    325         [Browsable(false)]
    326         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    327         public bool SelectionSupperScript
    328         {
    329             get
    330             {
    331                 return (SelectionCharOffset == 4);
    332             }
    333             set
    334             {
    335                 if (SelectionCharOffset == 0)
    336                 {
    337                     SelectionCharOffset =  4;
    338                 }
    339                 else
    340                 {
    341                     SelectionCharOffset = 0;
    342                 }
    343             }
    344         }
    345 
    346         /// <summary>
    347         /// 设置下标
    348         /// </summary>
    349         [Browsable(false)]
    350         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    351         public bool SelectionSubScript
    352         {
    353             get
    354             {
    355                 return (SelectionCharOffset == -4);
    356             }
    357             set
    358             {
    359                 if (SelectionCharOffset == 0)
    360                 {
    361                     SelectionCharOffset = -4;
    362                 }
    363                 else
    364                 {
    365                     SelectionCharOffset = 0;
    366                 }
    367 
    368             }
    369         }
    370  
    371 
    372         /// <summary>
    373         ///RichTextBox  数字序列 1. 2. 3. 4. 5.  ... 
    374         /// </summary>
    375         [Browsable(false)]
    376         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    377         public bool SelectionOrderList
    378         {
    379             get
    380             {
    381                 richTextBoxBulletClass r = new richTextBoxBulletClass();
    382                 r.richTextBox = this;
    383                 return r.SelectionOrderList;
    384             }
    385             set
    386             {
    387                 richTextBoxBulletClass r = new richTextBoxBulletClass();
    388                 r.richTextBox = this;
    389                 r.SelectionOrderList = value;
    390             }
    391         }
    392      
    393     
    394         //只须设置 不需要获得是否设置的返回值
    395         ////Tab->
    396         public void Indent()
    397         {
    398             SelectionIndent += 8;
    399         }
    400         ////Tab <-
    401         public void OutIndent()
    402         {
    403             SelectionIndent -= 8;
    404         }
    405 
    406         #endregion
    407 
    408         #region  RichTextBox Margin
    409         private struct Rect
    410         {
    411             public int Left;
    412             public int Top;
    413             public int Right;
    414             public int Bottom;
    415         }
    416 
    417         [DllImport("user32.dll")]
    418         private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref Rect lParam);
    419 
    420         private const int EM_GETRECT = 0x00b2;
    421         private const int EM_SETRECT = 0x00b3;
    422 
    423         /// <summary>
    424         /// 当没设置的时候结果多出了L T R +2
    425         /// </summary>
    426         private Rect RichTextBoxMargin
    427         {
    428             get
    429             {
    430                 Rect rect = new Rect();
    431                 SendMessage(richTextBox1.Handle, EM_GETRECT, IntPtr.Zero, ref rect);
    432                 rect.Left += 1;
    433                 rect.Top += 1;
    434                 rect.Right = 1 + richTextBox1.DisplayRectangle.Width - rect.Right;
    435                 rect.Bottom = richTextBox1.DisplayRectangle.Height - rect.Bottom;
    436                 return rect;
    437             }
    438             set
    439             {
    440                 Rect rect;
    441                 rect.Left = richTextBox1.ClientRectangle.Left + value.Left;
    442                 rect.Top = richTextBox1.ClientRectangle.Top + value.Top;
    443                 rect.Right = richTextBox1.ClientRectangle.Right - value.Right;
    444                 rect.Bottom = richTextBox1.ClientRectangle.Bottom - value.Bottom;
    445 
    446                 SendMessage(richTextBox1.Handle, EM_SETRECT, IntPtr.Zero, ref rect);
    447             }
    448 
    449         }
    450 
    451         [Browsable(true)]
    452         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    453         public int LeftMargin
    454         {
    455             get
    456             {
    457                 return RichTextBoxMargin.Left;
    458             }
    459             set
    460             {
    461                 Rect rect1;
    462                 rect1 = RichTextBoxMargin;
    463 
    464                 Rect rect;
    465                 rect.Left = value;
    466                 rect.Top = 0;//rect1.Top;
    467                 rect.Right = rect1.Right;
    468                 rect.Bottom = rect1.Bottom;
    469 
    470                 RichTextBoxMargin = rect;
    471             }
    472         }
    473 
    474         [Browsable(false)]
    475         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    476         public  int RightMargin
    477         {
    478             get
    479             {
    480                 return RichTextBoxMargin.Right;
    481             }
    482             set
    483             {
    484                 Rect rect1;
    485                 rect1 = RichTextBoxMargin;
    486 
    487                 Rect rect;
    488                 rect.Left = rect1.Left;
    489                 rect.Top = rect1.Top;
    490                 rect.Right = value;
    491                 rect.Bottom = rect1.Bottom;
    492 
    493                 RichTextBoxMargin = rect;
    494             }
    495         }
    496 
    497         [Browsable(false)]
    498         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    499         public int TopMargin
    500         {
    501             get
    502             {
    503                 return RichTextBoxMargin.Top;
    504             }
    505             set
    506             {
    507                 Rect rect1;
    508                 rect1 = RichTextBoxMargin;
    509 
    510                 Rect rect;
    511                 rect.Left = rect1.Left;
    512                 rect.Top = value;
    513                 rect.Right = rect1.Right;
    514                 rect.Bottom = rect1.Bottom;
    515 
    516                 RichTextBoxMargin = rect;
    517             }
    518         }
    519         [Browsable(false)]
    520         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    521         public int BottomMargin
    522         {
    523             get
    524             {
    525                 return RichTextBoxMargin.Bottom;
    526             }
    527             set
    528             {
    529                 Rect rect1;
    530                 rect1 = RichTextBoxMargin;
    531 
    532                 Rect rect;
    533                 rect.Left = rect1.Left;
    534                 rect.Top = rect1.Top;
    535                 rect.Right = rect1.Right;
    536                 rect.Bottom = value;
    537                 RichTextBoxMargin = rect;
    538             }
    539         }
    540 
    541 #endregion
    542         
    543         #region RichTextBox 默认快捷键
    544         /*
    545             查找    CTRL+F
    546             替换    CTRL+R
    547             时间日期     F5
    548 
    549             粗体    CTRL+B
    550             斜体    CTRL+I
    551             下划线    CTRL+U
    552          */
    553 
    554         protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    555         {
    556             if (!this.ReadOnly)
    557             {
    558                 switch (keyData)
    559                 {
    560                     //CTRL+B
    561                     case Keys.Control | Keys.B:
    562                         ToggleBold();
    563                         return true;
    564 
    565                     //CTRL+I
    566                     case Keys.Control | Keys.I:
    567                         ToggleItalic();
    568                         return true;
    569 
    570                     //CTRL+U
    571                     case Keys.Control | Keys.U:
    572                         ToggleUnderLine();
    573                         return true;
    574 
    575                     //shift +tab 左缩进
    576                     case Keys.Shift | Keys.Tab:
    577                         if (SelectedText != "")
    578                         {
    579                             SelectionIndent -= 8;
    580                         }
    581                         return true;
    582 
    583                     //shift +tab 右缩进
    584                     case Keys.Tab:
    585                         if (SelectedText != "")
    586                         {
    587                             SelectionIndent += 8;
    588                           
    589                         }
    590                         return true;
    591 
    592                     //替换对话框
    593                     case Keys.Control | Keys.R:
    594                         ShowReplaceDlg();
    595                         return true;
    596 
    597                     //插入时间日期
    598                     case Keys.F5:
    599                         //2013-11-25 13:57:09
    600                         SelectedText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
    601                         return true;
    602 
    603                     //粘贴纯文本
    604                     case Keys.Control | Keys.Shift | Keys.V:
    605                         PasteAsText();
    606                         return true;
    607 
    608                     case Keys.Control | Keys.G:
    609                         ShowGoToDlg();
    610                 return true;
    611 
    612                 }
    613             }
    614  
    615             if (keyData == (Keys.Control | Keys.F))
    616             {
    617                 ShowFindDlg();
    618             }
    619             return false;
    620         }
    621 
    622 
    623         #endregion
    624 
    625         #region RichTextBox 常用属性
    626 
    627         public void PasteAsText()
    628         {
    629             richTextBox1.SelectedText = Clipboard.GetText(); //粘贴纯文本
    630         }
    631 
    632         public void PasteAsBmp()
    633         {
    634             if (CanPasteAsBmp())
    635             {
    636                 richTextBox1.Paste();
    637             }
    638         }
    639 
    640         public void  PasteAsHtml()
    641         {
    642            
    643         }
    644 
    645         public void PasteAsUnicode()
    646         {
    647 
    648         }
    649 
    650         /// <summary>
    651         /// 剪切板是否为空
    652         /// </summary>
    653         /// <returns></returns>
    654         public  bool CanPaste()
    655         {
    656             return (Clipboard.GetDataObject() != null);
    657         }
    658 
    659         /// <summary>
    660         /// 剪切板是否有字符串
    661         /// </summary>
    662         /// <returns></returns>
    663         public bool CanPasteAsText()
    664         {
    665             return Clipboard.GetDataObject().GetDataPresent(DataFormats.Text); 
    666         }
    667         /// <summary>
    668         /// 剪切板是否有位图
    669         /// </summary>
    670         /// <returns></returns>
    671         public bool CanPasteAsBmp()
    672         {
    673             return Clipboard.GetDataObject().GetDataPresent(DataFormats.Bitmap); 
    674         }
    675         /// <summary>
    676         /// 剪切板是否HTML
    677         /// </summary>
    678         /// <returns></returns>
    679         public bool CanPasteAsHtml()
    680         {
    681             return Clipboard.GetDataObject().GetDataPresent(DataFormats.Html); 
    682         }
    683 
    684         /// <summary>
    685         /// 是否可以全选
    686         /// </summary>
    687         /// <returns></returns>
    688         public bool CanSelectAll()
    689         {
    690             return (richTextBox1.SelectedText.Length != richTextBox1.Text.Length);
    691         }
    692 
    693         private void InitialRichTextBoxCtrl()
    694         {
    695             //ContextMenuStrip = contextMenuStrip1;
    696             LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(richTextBox1_LinkClicked); 
    697         }
    698 
    699         /// <summary>
    700         /// 自动打开超链接
    701         /// </summary>
    702         /// <param name="sender"></param>
    703         /// <param name="e"></param>
    704         private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
    705         {
    706             DialogResult b = MessageBox.Show("你要打开此链接吗?
    " + e.LinkText, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
    707             if (b == DialogResult.Yes)
    708             {
    709                 System.Diagnostics.Process.Start("iexplore.exe", e.LinkText);
    710             }
    711         }
    712 
    713 
    714         #endregion
    715 
    716         #region RichTextBox 通用对话框
    717 
    718         //private FindDialog FindDlg = new FindDialog();
    719         //private ReplaceDialog ReplaceDlg=new ReplaceDialog();
    720 
    721         /// <summary>
    722         /// 查找对话框
    723         /// </summary>
    724         public void ShowFindDlg()
    725         {
    726             FindDialog FindDlg = new FindDialog();
    727             FindDlg.richTextBox1 = this;
    728             FindDlg.textBox1.Text = this.SelectedText;
    729             FindDlg.StartPosition = FormStartPosition.CenterParent;
    730             FindDlg.ShowDialog();
    731         }
    732 
    733         /// <summary>
    734         /// 替换 对话框
    735         /// </summary>
    736         public void ShowReplaceDlg()
    737         {
    738             ReplaceDialog ReplaceDlg = new ReplaceDialog();
    739             ReplaceDlg.StartPosition = FormStartPosition.CenterParent;
    740             ReplaceDlg.richTextBox1 = this;
    741             ReplaceDlg.textBox1.Text = this.SelectedText;
    742             ReplaceDlg.ShowDialog();
    743         }
    744 
    745         /// <summary>
    746         /// 字体对话框
    747         /// </summary>
    748         public void ShowFontDlg()
    749         {
    750             FontDialog fontDialog1 = new FontDialog();
    751             fontDialog1.Font = richTextBox1.Font;
    752             if (fontDialog1.ShowDialog() == DialogResult.OK)
    753             {
    754                 richTextBox1.Font = fontDialog1.Font;
    755 
    756             }
    757         }
    758         /// <summary>
    759         /// 转到 对话框
    760         /// </summary>
    761         public void ShowGoToDlg()
    762         {
    763             Point pt = this.GetCaretPosition();
    764 
    765             frm_GOTO frm = new frm_GOTO();
    766             frm.label1.Text = "等号(1 - " + this.Lines.Length.ToString() + ")(&L)";         
    767             frm.textBox1.Text = pt.X.ToString();
    768             if (frm.ShowDialog() == DialogResult.OK)
    769             {
    770                 int Line = Convert.ToInt32(frm.textBox1.Text);
    771                 if (Line >= 1)
    772                 {
    773                     if (Line > this.Lines.Length+1)
    774                     {
    775                         MessageBox.Show("行数大于现有的行数");
    776                     }
    777                     else
    778                     {
    779                         this.jumpLine(Line);
    780                     }
    781                 }
    782             }
    783         }
    784 
    785         //RichTextBox 插入图片
    786         public void ShowInsertImageDlg()
    787         {
    788             OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
    789             OpenFileDialog1.Title = "Select Image";
    790             OpenFileDialog1.Filter = "BMP File|*.BMP|JPEG File|*.JPG|GIF File|*.GIF|PNG File|*.PNG|ICO File|*.ICO|Image File|*.BMP;*.DIB;*.RLE;*.JPG;*.JPEG;*.JPE;*.JFIF;*.GIF;*.EMF;*.WMF;*.TIF;*.PNG;*.ICO|All File|*.*";
    791             OpenFileDialog1.FilterIndex = 6;
    792             if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
    793             {
    794                 string strImagePath = OpenFileDialog1.FileName;
    795                 Image img;
    796                 img = Image.FromFile(strImagePath);
    797                 Clipboard.SetDataObject(img);
    798                 DataFormats.Format df;
    799                 df = DataFormats.GetFormat(DataFormats.Bitmap);
    800                 if (this.CanPaste(df))
    801                 {
    802                     this.Paste(df);
    803                 }
    804             }
    805         }     
    806 
    807         //插入表格对话框
    808         public void ShowInsertTableDlg()
    809         {
    810             richTextBoxTableDlg dlg = new richTextBoxTableDlg();
    811             dlg.richTextBox = this;
    812 
    813             if (dlg.ShowDialog() == DialogResult.OK)
    814             {
    815                 richTextBoxTable r1 = new richTextBoxTable();
    816                 r1.richTextBox = this;
    817                 r1.cellWidth = (int)dlg.numericUpDownCellWidth.Value;
    818                 r1.InsertTable((int)dlg.numericUpDownColumn.Value, (int)dlg.numericUpDownRow.Value, dlg.radioButtonAutoSzie.Checked);
    819             }
    820         }
    821 
    822 
    823         public void ShowViewSourceDlg()
    824         {
    825             ViewRtfSoruceDlg rtfdlg = new ViewRtfSoruceDlg();
    826 
    827             string s = string.Format("文件很大 请等待... {0}KB", (richTextBox1.Rtf.Length /1204));
    828          
    829             //if (richTextBox1.Rtf.Length > 1024*1024)
    830             //    MessageBox.Show(s);
    831 
    832             rtfdlg.textBox1.Text = richTextBox1.Rtf;
    833             if (rtfdlg.ShowDialog()==DialogResult.OK)
    834             {
    835                 richTextBox1.Rtf = rtfdlg.textBox1.Text;
    836             }
    837             Application.DoEvents();
    838         }
    839         #endregion
    840 
    841         #region RichTextBox 是否显示行号
    842         #endregion
    843 
    844         #region 实现 页面设置  打印预览 打印
    845 
    846         //页面设置
    847         public void ShowPageSetupDlg()
    848         {
    849             richTextBoxPrintClass r = new richTextBoxPrintClass();
    850             r.richTextBox = this;
    851             r.ShowPageSetupDlg();
    852         }
    853         //打印预览功能
    854         public void ShowShowPagePriviewDlg()
    855         {
    856             richTextBoxPrintClass r = new richTextBoxPrintClass();
    857             r.richTextBox = this;
    858             r.ShowShowPagePriviewDlg();
    859         }
    860 
    861         //打印
    862         public void ShowPrintDlg()
    863         {
    864             richTextBoxPrintClass r = new richTextBoxPrintClass();
    865             r.richTextBox = this;
    866             r.ShowPrintDlg();
    867         }
    868 #endregion
    869 
    870         #region 支持表格正确粘贴
    871 
    872         
    873         // P/Invoke declarations
    874         [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    875         private static extern IntPtr LoadLibrary(string path);
    876 
    877         private static IntPtr moduleHandle;
    878 
    879         protected override CreateParams CreateParams
    880         {
    881             get
    882             {
    883                 if (moduleHandle == IntPtr.Zero)
    884                 {
    885                     moduleHandle = LoadLibrary("msftedit.dll");
    886                     if ((long)moduleHandle < 0x20)
    887                     {
    888                         throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not load Msftedit.dll");
    889                     }
    890                 }
    891 
    892                 CreateParams createParams = base.CreateParams;
    893                 createParams.ClassName = "RichEdit50W";
    894                 if (this.Multiline)
    895                 {
    896                     if (((this.ScrollBars & RichTextBoxScrollBars.Horizontal) != RichTextBoxScrollBars.None) && !base.WordWrap)
    897                     {
    898                         createParams.Style |= 0x100000;
    899                         if ((this.ScrollBars & ((RichTextBoxScrollBars)0x10)) != RichTextBoxScrollBars.None)
    900                         {
    901                             createParams.Style |= 0x2000;
    902                         }
    903                     }
    904                     if ((this.ScrollBars & RichTextBoxScrollBars.Vertical) != RichTextBoxScrollBars.None)
    905                     {
    906                         createParams.Style |= 0x200000;
    907                         if ((this.ScrollBars & ((RichTextBoxScrollBars)0x10)) != RichTextBoxScrollBars.None)
    908                         {
    909                             createParams.Style |= 0x2000;
    910                         }
    911                     }
    912                 }
    913                 if ((BorderStyle.FixedSingle == base.BorderStyle) && ((createParams.Style & 0x800000) != 0))
    914                 {
    915                     createParams.Style &= -8388609;
    916                     createParams.ExStyle |= 0x200;
    917                 }
    918                 return createParams;
    919             }
    920         }
    921         #endregion
    922     }
    923 
    924 }
    RichTextBoxCtrl.CS

    //

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Text;
      4 using System.Windows.Forms;
      5 using System.Runtime.InteropServices;
      6 
      7 
      8 //2013-11-27 02:00:13
      9 ////清除样式
     10 //richTextBoxBulletClass r = new richTextBoxBulletClass();
     11 //r.richTextBox = richTextBox1;
     12 //r.RemoveSelectionParaFormat2();
     13 
     14 
     15 ////属性获得
     16 
     17 //richTextBoxBulletClass r = new richTextBoxBulletClass();
     18 //r.richTextBox = richTextBox1;
     19 //btn.Checked = r.SelectionOrderList;
     20 
     21 
     22 ////设置样式
     23 //richTextBoxBulletClass r = new richTextBoxBulletClass();
     24 //r.richTextBox = richTextBox1;
     25 //r.SelectionOrderList = !r.SelectionOrderList;
     26 
     27 namespace RichTextBoxCtrl
     28 {
     29     class richTextBoxBulletClass
     30     {
     31         public RichTextBox richTextBox;
     32         public richTextBoxBulletClass()
     33         {
     34             richTextBox = new RichTextBox();
     35         }
     36 
     37         #region PARAFORMAT2
     38         [StructLayout(LayoutKind.Sequential)]
     39         private class PARAFORMAT2
     40         {
     41             public int cbSize;
     42             public int dwMask;
     43             public short wNumbering;
     44             public short wReserved;
     45             public int dxStartIndent;
     46             public int dxRightIndent;
     47             public int dxOffset;
     48             public short wAlignment;
     49             public short cTabCount;
     50             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)]
     51             public int[] rgxTabs;
     52 
     53             public int dySpaceBefore;     // Vertical spacing before para
     54             public int dySpaceAfter;     // Vertical spacing after para
     55             public int dyLineSpacing;     // Line spacing depending on Rule
     56             public short sStyle;         // Style handle
     57             public byte bLineSpacingRule;     // Rule for line spacing (see tom.doc)
     58             public byte bOutlineLevel;     // Outline Level
     59             public short wShadingWeight;     // Shading in hundredths of a per cent
     60             public short wShadingStyle;     // Byte 0: style, nib 2: cfpat, 3: cbpat
     61             public short wNumberingStart;     // Starting value for numbering
     62             public short wNumberingStyle;     // Alignment, Roman/Arabic, (), ), ., etc.
     63             public short wNumberingTab;     // Space bet 1st indent and 1st-line text
     64             public short wBorderSpace;     // Border-text spaces (nbl/bdr in pts)
     65             public short wBorderWidth;     // Pen widths (nbl/bdr in half twips)
     66             public short wBorders;         // Border styles (nibble/border)
     67 
     68             public PARAFORMAT2()
     69             {
     70                 this.cbSize = Marshal.SizeOf(typeof(PARAFORMAT2));
     71             }
     72         }
     73         #endregion
     74 
     75         #region PARAFORMAT MASK VALUES
     76 
     77 
     78 
     79         public const uint WM_USER = 0x0400;
     80         // RichEdit messages 
     81         public const uint EM_GETPARAFORMAT = (WM_USER + 61);
     82         public const uint EM_SETPARAFORMAT = (WM_USER + 71);
     83 
     84         // PARAFORMAT mask values
     85         public const uint PFM_OFFSET = 0x00000004;
     86         public const uint PFM_NUMBERING = 0x00000020;
     87 
     88         // PARAFORMAT 2.0 masks and effects
     89         public const uint PFM_NUMBERINGSTYLE = 0x00002000;//设置项目编号的样式
     90         public const uint PFM_NUMBERINGTAB = 0x00004000;//设置项目编号按下Tab键的信息
     91         public const uint PFM_NUMBERINGSTART = 0x00008000;//设置项目编号的开始标识
     92 
     93 
     94 
     95         //wNumbering
     96         //Options used for bulleted or numbered paragraphs. 
     97         //To use this member, set the PFM_NUMBERING flag in the dwMask member. 
     98         //This member can be one of the following values.
     99         public enum Paraformat2Numbering
    100         {
    101             zero = 0,
    102             Normal = 1,             //No paragraph numbering or bullets.
    103             ArabicNumbers = 2,      //Uses Arabic numbers (1, 2, 3, ...). 
    104             LowerCaseLetter = 3,    //Uses lowercase letters (a, b, c, ...). 
    105             UpperCaseLetter = 4,    //Uses uppercase letters (A, B, C, ...). 
    106             LowerCaseRoman = 5,     //Uses lowercase Roman numerals (i, ii, iii, ...). 
    107             UpperCaseRoman = 6      //Uses uppercase Roman numerals (I, II, III, ...). 
    108         }
    109 
    110         //wNumberingStyle
    111         //Numbering style used with numbered paragraphs. 
    112         //Use this member in conjunction with the wNumbering member. 
    113         //This member is included only for compatibility with TOM interfaces;
    114         //the rich edit control stores the value but rich edit versions earlier than 3.0 do not use it to display the text or bullets.
    115         //To use this member, set the PFM_NUMBERINGSTYLE flag in the dwMask member. 
    116         //This member can be one of the following values. 
    117         public enum Paraformat2NumberingStyle
    118         {
    119             RightParenthesis = 0x000,//Follows the number with a right parenthesis.
    120             DoubleParenthesis = 0x100,//Encloses the number in parentheses.
    121             Period = 0x200,//Follows the number with a period.
    122             Plain = 0x300,//Displays only the number.
    123             zero = 0x400//Continues a numbered list without applying the next number or bullet. 
    124         }
    125 
    126         #endregion
    127 
    128         #region SetSelectionParaFormat2
    129 
    130         [DllImport("user32.dll")]
    131         private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, uint wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] PARAFORMAT2 lParam);
    132 
    133         public void SetSelectionParaFormat2(Paraformat2NumberingStyle style, Paraformat2Numbering Number)
    134         {
    135             PARAFORMAT2 p = new PARAFORMAT2();
    136             p.dwMask = (int)(PFM_NUMBERING | PFM_OFFSET | PFM_NUMBERINGSTART | PFM_NUMBERINGSTYLE | PFM_NUMBERINGTAB);
    137 
    138             p.wNumbering = (short)Number;
    139             //p.dxOffset = BulletIndent;
    140             p.wNumberingStyle = (short)style;
    141             p.wNumberingStart = 1;
    142             p.wNumberingTab = 500;
    143 
    144             SendMessage(richTextBox.Handle, EM_SETPARAFORMAT, 0, p);
    145         }
    146         #endregion
    147 
    148 
    149         //获得 wNumbering的返回值
    150         public Paraformat2Numbering GetSelectionParaformat2wNumbering()
    151         {
    152             PARAFORMAT2 p = new PARAFORMAT2();
    153             SendMessage(richTextBox.Handle, EM_GETPARAFORMAT, 0, p);
    154             return (Paraformat2Numbering)p.wNumbering;
    155         }
    156 
    157         //获得wNumberingStyleg的返回值
    158         public Paraformat2NumberingStyle GetSelectionParaformat2wNumberingStyle()
    159         {
    160             PARAFORMAT2 p = new PARAFORMAT2();
    161             SendMessage(richTextBox.Handle, EM_GETPARAFORMAT, 0, p);
    162             return (Paraformat2NumberingStyle)p.wNumberingStyle;
    163         }
    164 
    165         #region 更多样式... ...
    166 
    167         private void test()
    168         {
    169             //●●●●
    170             SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.Normal);
    171             //1 2 3 4 5 ...
    172             SetSelectionParaFormat2(Paraformat2NumberingStyle.Plain, Paraformat2Numbering.ArabicNumbers);
    173             //1. 2. 3. 4. 5.  ...
    174             SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.ArabicNumbers);
    175             //1) 2) 3) 4) ...
    176             SetSelectionParaFormat2(Paraformat2NumberingStyle.RightParenthesis, Paraformat2Numbering.ArabicNumbers);
    177             //(1) (2) (3) (4) ...
    178             SetSelectionParaFormat2(Paraformat2NumberingStyle.DoubleParenthesis, Paraformat2Numbering.ArabicNumbers);
    179             //////////////////////////////////////////////////////////////////////////
    180 
    181             //a b c d e 
    182             SetSelectionParaFormat2(Paraformat2NumberingStyle.Plain, Paraformat2Numbering.LowerCaseLetter);
    183             //a. b. c. d. e.
    184             SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.LowerCaseLetter);
    185             //a) b) c) d) e)
    186             SetSelectionParaFormat2(Paraformat2NumberingStyle.RightParenthesis, Paraformat2Numbering.LowerCaseLetter);
    187             //(a) (b) (c) (d) (e)
    188             SetSelectionParaFormat2(Paraformat2NumberingStyle.DoubleParenthesis, Paraformat2Numbering.LowerCaseLetter);
    189             //////////////////////////////////////////////////////////////////////////
    190 
    191             //A B C D E 
    192             SetSelectionParaFormat2(Paraformat2NumberingStyle.Plain, Paraformat2Numbering.UpperCaseLetter);
    193             //A. B. C. D. E.
    194             SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.UpperCaseLetter);
    195             //A) B) C) D) E)
    196             SetSelectionParaFormat2(Paraformat2NumberingStyle.RightParenthesis, Paraformat2Numbering.UpperCaseLetter);
    197             //(A) (B) (C) (D) (E)
    198             SetSelectionParaFormat2(Paraformat2NumberingStyle.DoubleParenthesis, Paraformat2Numbering.UpperCaseLetter);
    199             //////////////////////////////////////////////////////////////////////////
    200 
    201             //I II III IIII IV 
    202             SetSelectionParaFormat2(Paraformat2NumberingStyle.Plain, Paraformat2Numbering.LowerCaseRoman);
    203             //I. II. III. IIII. IV. 
    204             SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.LowerCaseRoman);
    205             //I) II) III) IIII) IV) 
    206             SetSelectionParaFormat2(Paraformat2NumberingStyle.RightParenthesis, Paraformat2Numbering.LowerCaseRoman);
    207             //(I) (II) (III) (IIII) (IV) 
    208             SetSelectionParaFormat2(Paraformat2NumberingStyle.DoubleParenthesis, Paraformat2Numbering.LowerCaseRoman);
    209             //////////////////////////////////////////////////////////////////////////
    210 
    211         }
    212         #endregion
    213 
    214 
    215 
    216         //清除选中的样式
    217         public void RemoveSelectionParaFormat2()
    218         {
    219             SetSelectionParaFormat2(0, 0);
    220         }
    221 
    222 
    223 
    224         #region  数字序列 1. 2. 3. 4. 5.  ...
    225         private bool bOrder = false;
    226         public bool SelectionOrderList
    227         {
    228             get
    229             {
    230                 return (
    231                        (GetSelectionParaformat2wNumbering() == Paraformat2Numbering.ArabicNumbers) &&
    232                        (GetSelectionParaformat2wNumberingStyle() == Paraformat2NumberingStyle.Period)
    233                        );
    234 
    235             }
    236             set
    237             {
    238                 bOrder = value;
    239 
    240                 if (value == true)
    241                     SetSelectionParaFormat2(Paraformat2NumberingStyle.Period, Paraformat2Numbering.ArabicNumbers);
    242                 else
    243                     RemoveSelectionParaFormat2();
    244             }
    245         }
    246         #endregion
    247 
    248     }
    249 }
    richTextBoxBulletClass.CS

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Windows.Forms;
      6 using System.Drawing;
      7 
      8 
      9 //使用
     10 ////set font Size font Style bold Italic
     11 ////
     12 ////普通  not bold italic 
     13 ////标题1  字体大小 24 Bold
     14 ////标题2  字体大小 18 Bold
     15 ////标题3  字体大小 14 Bold
     16 ////标题4  字体大小 12 Bold
     17 ////标题5  字体大小 10 Bold
     18 ////标题6  字体大小 8  Bold
     19 ////地址   字体大小 12 Italic
     20 
     21 //private RichTextBoxCtrl.richTextBoxFontFormatClass r = new RichTextBoxCtrl.richTextBoxFontFormatClass();
     22 //private void Form1_Load(object sender, EventArgs e)
     23 //{
     24 //    r.richTextBox = richTextBox1;
     25 //    comboBox1.Items.Clear();
     26 //    comboBox1.Items.AddRange(new object[] {
     27 //             "普通",
     28 //             "标题1",
     29 //             "标题2",
     30 //             "标题3",
     31 //             "标题4",
     32 //             "标题5",
     33 //             "标题6",
     34 //             "地址 "});
     35 //}
     36 
     37 //private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
     38 //{
     39 //    r.SetFontFormat(comboBox1.SelectedIndex);
     40 
     41 //    //SetFontFormat(comboBox1.SelectedIndex);
     42 //    Text = r.GetFontFormat().ToString();
     43 //}
     44 
     45 //private void richTextBox1_SelectionChanged(object sender, EventArgs e)
     46 //{
     47 //    Text = r.GetFontFormat();
     48 //    comboBox1.Text = r.GetFontFormat();
     49 //}
     50 
     51 namespace RichTextBoxCtrl
     52 {
     53     class richTextBoxFontFormatClass
     54     {
     55         public richTextBoxFontFormatClass()
     56         {
     57 
     58         }
     59         public RichTextBox richTextBox;
     60       
     61         public void SetFontFormat(int formatIndex)
     62         {
     63             float fontSize = richTextBox.Font.Size;
     64             string fontName = richTextBox.Font.Name;
     65             switch (formatIndex)
     66             {
     67                 case 0://普通
     68                     richTextBox.SelectionFont = new Font(fontName, fontSize, FontStyle.Regular);
     69                     break;
     70                 case 1://标题1 
     71                     richTextBox.SelectionFont = new Font(fontName, 24f, FontStyle.Bold);
     72                     break;
     73                 case 2: //标题2
     74                     richTextBox.SelectionFont = new Font(fontName, 18f, FontStyle.Bold);
     75                     break;
     76                 case 3: //标题3
     77                     richTextBox.SelectionFont = new Font(fontName, 14f, FontStyle.Bold);
     78                     break;
     79                 case 4://标题4
     80                     richTextBox.SelectionFont = new Font(fontName, 12f, FontStyle.Bold);
     81                     break;
     82                 case 5: //标题5
     83                     richTextBox.SelectionFont = new Font(fontName, 10f, FontStyle.Bold);
     84                     break;
     85                 case 6: //标题6
     86                     richTextBox.SelectionFont = new Font(fontName, 8f, FontStyle.Bold);
     87                     break;
     88                 case 7: //地址
     89                     richTextBox.SelectionFont = new Font(fontName, 12f, FontStyle.Italic);
     90                     break;
     91             }
     92         }
     93         public string GetFontFormat()
     94         {
     95             string Result = "普通";
     96             if (richTextBox.SelectionFont !=null )
     97             {           
     98                 float fontSize = richTextBox.SelectionFont.Size;
     99                 FontStyle fontStyle = richTextBox.SelectionFont.Style;
    100 
    101                 if (fontSize == 24 && fontStyle == FontStyle.Bold)
    102                     Result = "标题1";
    103                 else
    104                 if (fontSize == 18 && fontStyle == FontStyle.Bold)
    105                     Result = "标题2";
    106                 else
    107                 if (fontSize == 14 && fontStyle == FontStyle.Bold)
    108                     Result = "标题3";
    109                 else
    110                 if (fontSize == 12 && fontStyle == FontStyle.Bold)
    111                     Result = "标题4";
    112                 else
    113                 if (fontSize == 10 && fontStyle == FontStyle.Bold)
    114                     Result = "标题5";
    115                 else
    116                 if (fontSize == 8 && fontStyle == FontStyle.Bold)
    117                     Result = "标题6";
    118                 else
    119                 if (fontSize == 12 && fontStyle == FontStyle.Italic)
    120                     Result = "地址";
    121                 else
    122                     Result = "普通";
    123             }
    124             else
    125                 Result = "普通";
    126             return Result;
    127         }
    128     }
    129 }
    richTextBoxFontFormatClass.CS

      1 using System;
      2 using System.Windows.Forms;
      3 using System.Drawing;
      4 using System.Runtime.InteropServices;
      5 using System.Drawing.Printing;
      6 
      7 
      8 #region 调用示例
      9 /*使用
     10 //页面设置
     11 private void btnPageSetup_Click(object sender, EventArgs e)
     12 {
     13     richTextBoxPrintClass r = new richTextBoxPrintClass();
     14     r.richTextBox = richTextBox1;
     15     r.ShowPageSetupDlg();
     16 }
     17 //打印预览功能
     18 private void btnPrintPreview_Click(object sender, EventArgs e)
     19 {
     20     richTextBoxPrintClass r = new richTextBoxPrintClass();
     21     r.richTextBox = richTextBox1;
     22     r.ShowShowPagePriviewDlg();
     23 }
     24 //打印
     25 private void btnPrint_Click(object sender, EventArgs e)
     26 {
     27     richTextBoxPrintClass r = new richTextBoxPrintClass();
     28     r.richTextBox = richTextBox1;
     29     r.ShowPrintDlg();
     30 }
     31 */
     32 #endregion
     33 //http://support.microsoft.com/kb/812425/zh-cn
     34 namespace RichTextBoxCtrl
     35 {
     36     class richTextBoxPrintClass
     37     {
     38         public richTextBoxPrintClass()
     39         {
     40             InitializeComponent();
     41         }
     42         #region 打印功用
     43 
     44         //and the unit used by Win32 API calls (twips 1/1440 inch)
     45         private const double anInch = 14.4;
     46 
     47         [StructLayout(LayoutKind.Sequential)]
     48         private struct RECT
     49         {
     50             public int Left;
     51             public int Top;
     52             public int Right;
     53             public int Bottom;
     54         }
     55 
     56         [StructLayout(LayoutKind.Sequential)]
     57         private struct CHARRANGE
     58         {
     59             public int cpMin;         //First character of range (0 for start of doc)
     60             public int cpMax;           //Last character of range (-1 for end of doc)
     61         }
     62 
     63         [StructLayout(LayoutKind.Sequential)]
     64         private struct FORMATRANGE
     65         {
     66             public IntPtr hdc;             //Actual DC to draw on
     67             public IntPtr hdcTarget;       //Target DC for determining text formatting
     68             public RECT rc;                //Region of the DC to draw to (in twips)
     69             public RECT rcPage;            //Region of the whole DC (page size) (in twips)
     70             public CHARRANGE chrg;         //Range of text to draw (see earlier declaration)
     71         }
     72 
     73         private const int WM_USER = 0x0400;
     74         private const int EM_FORMATRANGE = WM_USER + 57;
     75 
     76         [DllImport("USER32.dll")]
     77         private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
     78 
     79 
     80         // Render the contents of the RichTextBox for printing
     81         //    Return the last character printed + 1 (printing start from this point for next page)
     82         public static int Print(RichTextBox richTextBox, int charFrom, int charTo, PrintPageEventArgs e)
     83         {
     84             //Calculate the area to render and print
     85             RECT rectToPrint;
     86             rectToPrint.Top = (int)(e.MarginBounds.Top * anInch);
     87             rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * anInch);
     88             rectToPrint.Left = (int)(e.MarginBounds.Left * anInch);
     89             rectToPrint.Right = (int)(e.MarginBounds.Right * anInch);
     90 
     91             //Calculate the size of the page
     92             RECT rectPage;
     93             rectPage.Top = (int)(e.PageBounds.Top * anInch);
     94             rectPage.Bottom = (int)(e.PageBounds.Bottom * anInch);
     95             rectPage.Left = (int)(e.PageBounds.Left * anInch);
     96             rectPage.Right = (int)(e.PageBounds.Right * anInch);
     97 
     98             IntPtr hdc = e.Graphics.GetHdc();
     99 
    100             FORMATRANGE fmtRange;
    101             fmtRange.chrg.cpMax = charTo;                //Indicate character from to character to 
    102             fmtRange.chrg.cpMin = charFrom;
    103             fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
    104             fmtRange.hdcTarget = hdc;              //Point at printer hDC
    105             fmtRange.rc = rectToPrint;             //Indicate the area on page to print
    106             fmtRange.rcPage = rectPage;            //Indicate size of page
    107 
    108             IntPtr res = IntPtr.Zero;
    109 
    110             IntPtr wparam = IntPtr.Zero;
    111             wparam = new IntPtr(1);
    112 
    113             //Get the pointer to the FORMATRANGE structure in memory
    114             IntPtr lparam = IntPtr.Zero;
    115             lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
    116             Marshal.StructureToPtr(fmtRange, lparam, false);
    117 
    118             //Send the rendered data for printing 
    119             res = SendMessage(richTextBox.Handle, EM_FORMATRANGE, wparam, lparam);
    120 
    121             //Free the block of memory allocated
    122             Marshal.FreeCoTaskMem(lparam);
    123 
    124             //Release the device context handle obtained by a previous call
    125             e.Graphics.ReleaseHdc(hdc);
    126 
    127             //Return last + 1 character printer
    128             return res.ToInt32();
    129         }
    130 
    131         #endregion
    132 
    133 
    134         #region 初始化
    135         public RichTextBox richTextBox;
    136         private PageSetupDialog pageSetupDialog1;
    137         private PrintDialog printDialog1;
    138         private PrintDocument printDocument1;
    139         private PrintPreviewDialog printPreviewDialog1;
    140 
    141         private void InitializeComponent()
    142         {
    143             richTextBox = new RichTextBox();
    144             pageSetupDialog1 = new PageSetupDialog();
    145             printDialog1 = new PrintDialog();
    146             printDocument1 = new PrintDocument();
    147             printPreviewDialog1 = new PrintPreviewDialog();
    148 
    149             // 
    150             // pageSetupDialog1
    151             // 
    152             pageSetupDialog1.Document = printDocument1;
    153             // 
    154             // printDialog1
    155             // 
    156             printDialog1.Document = printDocument1;
    157             printDialog1.UseEXDialog = true;
    158             // 
    159             // printDocument1
    160             // 
    161             printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
    162             printDocument1.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument1_BeginPrint);
    163             // 
    164             // printPreviewDialog1
    165             // 
    166 
    167             printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
    168             printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
    169             printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
    170             printPreviewDialog1.Document = printDocument1;
    171             printPreviewDialog1.Enabled = true;
    172             // printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog1.Icon")));
    173             printPreviewDialog1.Name = "printPreviewDialog1";
    174             printPreviewDialog1.Visible = false;
    175         }
    176 
    177 
    178         private int checkPrint;
    179         private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    180         {
    181             checkPrint = 0;
    182         }
    183 
    184         private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    185         {
    186             // Print the content of RichTextBox. Store the last character printed.
    187             //checkPrint = richTextBoxPrintCtrl1.Print(checkPrint, richTextBoxPrintCtrl1.TextLength, e);
    188             checkPrint = richTextBoxPrintClass.Print(richTextBox, checkPrint, richTextBox.TextLength, e);
    189 
    190             // Check for more pages
    191             if (checkPrint < richTextBox.TextLength)
    192                 e.HasMorePages = true;
    193             else
    194                 e.HasMorePages = false;
    195         }
    196 
    197 
    198         #endregion
    199 
    200 
    201         //页面设置功能
    202         public void ShowPageSetupDlg()
    203         {
    204             pageSetupDialog1.ShowDialog();
    205         }
    206 
    207         //打印预览功能
    208         public void ShowShowPagePriviewDlg()
    209         {
    210             printPreviewDialog1.ShowDialog();
    211         }
    212 
    213         //打印
    214         public void ShowPrintDlg()
    215         {
    216             if (printDialog1.ShowDialog() == DialogResult.OK)
    217                 printDocument1.Print();
    218         }
    219     }
    220 }
    richTextBoxPrintClass.CS

     1 using System;
     2 using System.Runtime.InteropServices;
     3 using System.Windows.Forms;
     4 using System.Text;
     5 
     6 //private void button2_Click(object sender, EventArgs e)
     7 //{
     8 //    richTextBoxTableDlg dlg = new richTextBoxTableDlg();
     9 //    dlg.richTextBox = richTextBox51;
    10 
    11 //    if (dlg.ShowDialog() ==DialogResult.OK)
    12 //    {
    13 //        richTextBoxTable r1 = new richTextBoxTable();
    14 //        r1.richTextBox = richTextBox51;
    15 //        r1.cellWidth = (int)dlg.numericUpDownCellWidth.Value  ;
    16 //        r1.InsertTable((int)dlg.numericUpDownColumn.Value, (int)dlg.numericUpDownRow.Value, dlg.radioButtonAutoSzie.Checked);  
    17 //    }
    18 //}
    19 /*
    20  * 光标在表格上可以改变光标
    21  */
    22 
    23 namespace richTextBoxTableClass
    24 {
    25     public class richTextBoxTable 
    26     {
    27       
    28         public richTextBoxTable()
    29         {
    30 
    31         }
    32 
    33        public RichTextBox richTextBox;
    34        public int cellWidth;// = 1000;//default =1000
    35 
    36         /// <summary>
    37         /// 插入表格
    38         /// </summary>
    39         /// <param name="col"></param>
    40         /// <param name="row"></param>
    41         /// <param name="AutoSize">=TRUE:自动设置每个单元格的大小</param>
    42         public void InsertTable(int col, int row,bool AutoSize)
    43         {
    44             StringBuilder rtf = new StringBuilder();
    45             rtf.Append(@"{
    tf1 ");
    46 
    47             //int cellWidth = 1000;//col.1 width =1000
    48             if (AutoSize)
    49                 //滚动条出现时 (richTextBox.ClientSize.Width - 滚动条的宽 /列的个数)*15
    50                 cellWidth = ((richTextBox.ClientSize.Width-3) / row) * 15; 
    51             for (int i = 0; i < col; i++)
    52             {
    53                 rtf.Append(@"	rowd");
    54                 for (int j = 1; j <= row; j++)
    55                     rtf.Append(@"cellx" + (j * cellWidth).ToString());
    56                 rtf.Append(@"intbl cell 
    ow"); //create row
    57             }
    58             rtf.Append(@"pard");
    59             rtf.Append(@"}");
    60             richTextBox.SelectedRtf = rtf.ToString();
    61             //return rtf.ToString();
    62         }
    63     }
    64 }
    richTextBoxTableClass
  • 相关阅读:
    命令行程序测试自动化
    微软的PivotViewer控件编程续
    使用Autofac实现依赖注射及Ioc
    微软的PivotViewer控件编程
    求最大公约数(GCD)的两种算法
    编译原理学习笔记一(待续)
    如果你想创业,又担心腾讯照抄你的好点子的话,可以看看下面的文章。
    从测试的角度来重新反思我们自己的程序以及我们的程序员之路——“通过追本溯源来进行前瞻性思考”
    Ubuntu11.10安装飞信
    2012.3.27《JAVA程序设计教程》
  • 原文地址:https://www.cnblogs.com/xe2011/p/3473107.html
Copyright © 2011-2022 走看看