Dev Center > Windows Forms Forums > Windows Forms Sample Applications > Using rich text box for Text Editor

Unanswered Using rich text box for Text Editor

  • Thursday, August 20, 2009 10:23 AM
     
     
    Hi,

    I am using rich text box for text editor,here i getting features like msword,expet page numbers.

    Any tell to me how can i get page numbers in rich text box or atleast get page numbers in print level.

    Thanks,
    Venkat.C

All Replies

  • Monday, August 24, 2009 11:18 AM
    Moderator
     
      Has Code

    Hi Venkat,

     

    The link below shows how to print the RichTextBox control:
    http://support.microsoft.com/kb/812425.

     

    We can trace the print process to get the count of the pages.  This is the code snippet:

    Custom RichTextBox:

    public class RichTextBoxPrintCtrl : RichTextBox
    {        
        //Set the print document and add the print handler.
        public void SetPrintDocument(PrintDocument doc)
        {
            if (doc != null)
            {
                _doc = doc;
                _checkPrint = 0;
                _doc.PrintPage -= new PrintPageEventHandler(doc_PrintPage);
                _doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
            }
        }
    
        //Get the printed pages.
        public int GetPages()
        {
            return _pages;
        }
        
        void doc_PrintPage(object sender, PrintPageEventArgs e)
        {
            //Initialize the pages.
            if(_checkPrint == 0) _pages = 0;
            //Increment pages.
            ++_pages;
    
            // Print the content of RichTextBox. Store the last character printed.
            _checkPrint = this.Print(_checkPrint, this.TextLength, e);
    
            // Check for more pages
            if (_checkPrint < this.TextLength)
                e.HasMorePages = true;
            else
            {
                e.HasMorePages = false;
                _checkPrint = 0;
            }
        }
    
        //Print document.
        private PrintDocument _doc = null;
        //Trace each print.
        private int _checkPrint = 0;
        //Trace the printed pages.
        private int _pages = 0;
    
        #region Print implementation
        //Convert the unit used by the .NET framework (1/100 inch) 
        //and the unit used by Win32 API calls (twips 1/1440 inch)
        private const double anInch = 14.4;
    
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    
        [StructLayout(LayoutKind.Sequential)]
        private struct CHARRANGE
        {
            public int cpMin;         //First character of range (0 for start of doc)
            public int cpMax;         //Last character of range (-1 for end of doc)
        }
    
        [StructLayout(LayoutKind.Sequential)]
        private struct FORMATRANGE
        {
            public IntPtr hdc;             //Actual DC to draw on
            public IntPtr hdcTarget;       //Target DC for determining text formatting
            public RECT rc;                //Region of the DC to draw to (in twips)
            public RECT rcPage;            //Region of the whole DC (page size) (in twips)
            public CHARRANGE chrg;         //Range of text to draw (see earlier declaration)
        }
    
        private const int WM_USER = 0x0400;
        private const int EM_FORMATRANGE = WM_USER + 57;
    
        [DllImport("USER32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    
        // Render the contents of the RichTextBox for printing
        // Return the last character printed + 1 (printing start from this point for next page)
        public int Print(int charFrom, int charTo, PrintPageEventArgs e)
        {
            //Calculate the area to render and print
            RECT rectToPrint;
            rectToPrint.Top = (int)(e.MarginBounds.Top * anInch);
            rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * anInch);
            rectToPrint.Left = (int)(e.MarginBounds.Left * anInch);
            rectToPrint.Right = (int)(e.MarginBounds.Right * anInch);
    
            //Calculate the size of the page
            RECT rectPage;
            rectPage.Top = (int)(e.PageBounds.Top * anInch);
            rectPage.Bottom = (int)(e.PageBounds.Bottom * anInch);
            rectPage.Left = (int)(e.PageBounds.Left * anInch);
            rectPage.Right = (int)(e.PageBounds.Right * anInch);
    
            IntPtr hdc = e.Graphics.GetHdc();
    
            FORMATRANGE fmtRange;
            fmtRange.chrg.cpMax = charTo;		   //Indicate character from to character to 
            fmtRange.chrg.cpMin = charFrom;
            fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
            fmtRange.hdcTarget = hdc;              //Point at printer hDC
            fmtRange.rc = rectToPrint;             //Indicate the area on page to print
            fmtRange.rcPage = rectPage;            //Indicate size of page
    
            IntPtr res = IntPtr.Zero;
    
            IntPtr wparam = IntPtr.Zero;
            wparam = new IntPtr(1);
    
            //Get the pointer to the FORMATRANGE structure in memory
            IntPtr lparam = IntPtr.Zero;
            lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
            Marshal.StructureToPtr(fmtRange, lparam, false);
    
            //Send the rendered data for printing 
            res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);
    
            //Free the block of memory allocated
            Marshal.FreeCoTaskMem(lparam);
    
            //Release the device context handle obtained by a previous call
            e.Graphics.ReleaseHdc(hdc);
    
            //Return last + 1 character printer
            return res.ToInt32();
        } 
        #endregion
    
    }

     

     

    Test code:

    private void RichTextBoxPrintForm_Load(object sender, EventArgs e)
    {
        this.richTextBoxPrintCtrl1.Rtf = File.ReadAllText("TextBoxCtrl\\test.rtf");
        this.richTextBoxPrintCtrl1.SetPrintDocument(this.printDocument1);
        this.printPreviewDialog1.Show();
        this.printPreviewDialog1.Document.EndPrint += new PrintEventHandler(Document_EndPrint);
    }
    
    void Document_EndPrint(object sender, PrintEventArgs e)
    {
        MessageBox.Show(this.richTextBoxPrintCtrl1.GetPages().ToString());
    }

     

     

    Comment: When we want to get the count of the pages, we have to wait for the print process finished.

     

    Regards,

    Aland Li


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Monday, August 24, 2009 11:28 AM
     
     
    RichTextBox doesn't have any concept of 'pages' so you need to calculete it by youself during print depending on font size, paper size, print margins and so on. It's a huge job. You can use a simple approzimation to have a little less work to do by counting how many lines of text can be printed on a page using predifined you print margins and fot size.
    Eugene Mikhaylov http://www.codelibrary.ru
  • Monday, August 24, 2009 1:50 PM
     
     
    Hi Thank u for ur reply.

    Acyutal i had rich text box print code,in this i divied the complete text as pages,but when i give the print,that time i can get page number at top level or bottom level of each page.

    if possiable tell,i am faced these since 1 week.



    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Monday, August 24, 2009 1:51 PM
     
     
    Hi,
    tried another way,

    like this

    i am created rich text boxes diynamically,but i can't apply feauters,becases ,i didn't get id s for dynamic controls ids.

    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Tuesday, August 25, 2009 2:25 AM
    Moderator
     
     

    Hi Venkat,

    You said:
    Acyutal i had rich text box print code,in this i divied the complete text as pages,but when i give the print,that time i can get page number at top level or bottom level of each page.If you can do all of these, why you cannot get the page number? Do you mean you want to get page number before the print process?

    You also said:
    i am created rich text boxes diynamically,but i can't apply feauters,becases ,i didn't get id s for dynamic controls ids.You can define a member in the class and use it to store the instance of the RichTextBox.

    Let me know if this helps.
    Aland Li



    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Tuesday, August 25, 2009 5:31 AM
     
     
    Hi Aland,

    Thanks for ur reply.

    When i see print view,i can see pages,but i want page numbers show in every page.

    for send one can u give me code for that.

    i am using below code for dynamic create rich text box.


    private

     

    void richTextBox1_KeyDown(object sender, KeyEventArgs e)

    {

     

    if (e.KeyCode.Equals(Keys.Enter))

    {

     

    //RichTextBox box1 = new RichTextBox();

     

    //richTextBox1.MaximumSize = richTextBox1.Size;

     

    //richTextBox1.SelectionTabs=

     

    //if(richTextBox1.Height==147)

    RichTextBox box1 =

    new RichTextBox();

    box1.Location =

    new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 170);

    box1.Size = richTextBox1.Size;

    box1.KeyDown +=

    new KeyEventHandler(box_KeyDown);

     

    //this.Controls.Add(box);

     

    this.Controls.Add(box1);

    }

    }

     

    void box_KeyDown(object sender, KeyEventArgs e)

    {

     

    int i = 170;

     

    int j = Convert.ToInt32(this.Controls.Count.ToString());

     

    int z = i * j;

     

    //RichTextBox box = new RichTextBox();

    RichTextBox box1 =

    new RichTextBox();

    box1.Location =

    new Point(richTextBox1.Location.X, richTextBox1.Location.Y + z);

     

    //box.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 210);

    box1.Size = richTextBox1.Size;

    box1.KeyDown +=

    new KeyEventHandler(box_KeyDown);

     

    //this.Controls.Add(box);

     

    this.Controls.Add(box1);

     

    }


    please tell me how can i store each ids & how can get that particular id when click on rich text box


    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Tuesday, August 25, 2009 2:05 PM
     
     
    Hi,

    I am using panel ,in this panel add the rich text boxes at run time,then,give the print for panel,in this case ,every rich text box have one rich text box.

    So how can do.

    One thing, when i open document,

    its open in multi text bexes.

    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Wednesday, August 26, 2009 5:56 AM
     
     
    Hi ,

    I am add rich text boxes to panel,when i give the print panel,then i get each print page contain only one rich text box.

    thanks,
    Venkat


    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Thursday, August 27, 2009 7:45 AM
    Moderator
     
     
    Hi Venkat,

    Could you please let me know how you implemented the printing? It is appreciated if you could provide a code snippet?
    This thread shows how to print contents in a panel: http://social.msdn.microsoft.com/forums/en-US/winforms/thread/a9d02860-1510-4b0d-b752-903871c8c76b/.

    Regards,
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Thursday, August 27, 2009 8:50 AM
    Moderator
     
     
    Hi Venkat,

    Do you mean that you need to show a page number on each page, such as Page 1, page 2 and so on. The no. is shown on the top or the bottom of each page, just like printing a word document?

    Regards,
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Thursday, August 27, 2009 10:05 AM
     
     
    Hi,

    Yes Aland,Exactly i want like that,it is possiable ,when we use single rich text box
    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Thursday, August 27, 2009 10:09 AM
     
     
    Hi Aland,

    U sent one link na,i was use same code,but no use,when i print,it didn't show rich text box content(rich text box added to panel)
    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Thursday, August 27, 2009 10:14 AM
    Moderator
     
     
    Hi Venkat,

    This is the tread talking about how to print RichTextBox:
    http://social.msdn.microsoft.com/Forums/en-US/winformsapplications/thread/9160ad13-b2f8-4704-9966-1008b37b4712/.

    Is that the same issue as this thread? If so, I would like to merge them. 

    Regards,
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Thursday, August 27, 2009 10:28 AM
    Moderator
     
      Has Code
    Hi Venkat,

    This is the modified code snippet which I add a page number on the bottom of each page:
    public class RichTextBoxPrintCtrl : RichTextBox
        {
            //Set the print document and add the print handler.
            public void SetPrintDocument(PrintDocument doc)
            {
                if (doc != null)
                {
                    _doc = doc;
                    _checkPrint = 0;
                    _doc.PrintPage -= new PrintPageEventHandler(doc_PrintPage);
                    _doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
                }
            }
    
            //Get the printed pages.
            public int GetPages()
            {
                return _pages;
            }
    
            void doc_PrintPage(object sender, PrintPageEventArgs e)
            {
                //Initialize the pages.
                if (_checkPrint == 0) _pages = 0;
                //Increment pages.
                ++_pages;
    
                // Print the content of RichTextBox. Store the last character printed.
                _checkPrint = this.Print(_checkPrint, this.TextLength, e);
    
                //Draw the page number.
                Rectangle pageNoRect = Rectangle.FromLTRB(e.PageBounds.Left, e.PageBounds.Bottom - 20,
                    e.PageBounds.Right,e.PageBounds.Bottom);
                StringFormat format = new StringFormat{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
                e.Graphics.DrawString(string.Format("Page {0}", _pages), this.Font, Brushes.Black, pageNoRect, format);
    
                // Check for more pages
                if (_checkPrint < this.TextLength)
                    e.HasMorePages = true;
                else
                {
                    e.HasMorePages = false;
                    _checkPrint = 0;
                }
            }
    
            //Print document.
            private PrintDocument _doc = null;
            //Trace each print.
            private int _checkPrint = 0;
            //Trace the printed pages.
            private int _pages = 0;
    
            #region Print implementation
            //Convert the unit used by the .NET framework (1/100 inch) 
            //and the unit used by Win32 API calls (twips 1/1440 inch)
            private const double anInch = 14.4;
    
            [StructLayout(LayoutKind.Sequential)]
            private struct RECT
            {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;
            }
    
            [StructLayout(LayoutKind.Sequential)]
            private struct CHARRANGE
            {
                public int cpMin;         //First character of range (0 for start of doc)
                public int cpMax;         //Last character of range (-1 for end of doc)
            }
    
            [StructLayout(LayoutKind.Sequential)]
            private struct FORMATRANGE
            {
                public IntPtr hdc;             //Actual DC to draw on
                public IntPtr hdcTarget;       //Target DC for determining text formatting
                public RECT rc;                //Region of the DC to draw to (in twips)
                public RECT rcPage;            //Region of the whole DC (page size) (in twips)
                public CHARRANGE chrg;         //Range of text to draw (see earlier declaration)
            }
    
            private const int WM_USER = 0x0400;
            private const int EM_FORMATRANGE = WM_USER + 57;
    
            [DllImport("USER32.dll")]
            private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    
            // Render the contents of the RichTextBox for printing
            // Return the last character printed + 1 (printing start from this point for next page)
            public int Print(int charFrom, int charTo, PrintPageEventArgs e)
            {
                //Calculate the area to render and print
                RECT rectToPrint;
                rectToPrint.Top = (int)(e.MarginBounds.Top * anInch);
                rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * anInch);
                rectToPrint.Left = (int)(e.MarginBounds.Left * anInch);
                rectToPrint.Right = (int)(e.MarginBounds.Right * anInch);
    
                //Calculate the size of the page
                RECT rectPage;
                rectPage.Top = (int)(e.PageBounds.Top * anInch);
                rectPage.Bottom = (int)(e.PageBounds.Bottom * anInch);
                rectPage.Left = (int)(e.PageBounds.Left * anInch);
                rectPage.Right = (int)(e.PageBounds.Right * anInch);
    
                IntPtr hdc = e.Graphics.GetHdc();
    
                FORMATRANGE fmtRange;
                fmtRange.chrg.cpMax = charTo;		   //Indicate character from to character to 
                fmtRange.chrg.cpMin = charFrom;
                fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
                fmtRange.hdcTarget = hdc;              //Point at printer hDC
                fmtRange.rc = rectToPrint;             //Indicate the area on page to print
                fmtRange.rcPage = rectPage;            //Indicate size of page
    
                IntPtr res = IntPtr.Zero;
    
                IntPtr wparam = IntPtr.Zero;
                wparam = new IntPtr(1);
    
                //Get the pointer to the FORMATRANGE structure in memory
                IntPtr lparam = IntPtr.Zero;
                lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
                Marshal.StructureToPtr(fmtRange, lparam, false);
    
                //Send the rendered data for printing 
                res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);
    
                //Free the block of memory allocated
                Marshal.FreeCoTaskMem(lparam);
    
                //Release the device context handle obtained by a previous call
                e.Graphics.ReleaseHdc(hdc);
    
                //Return last + 1 character printer
                return res.ToInt32();
            }
            #endregion
    
        }
    Regards,
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Thursday, August 27, 2009 12:22 PM
     
     
    Hi Aland,

    Thanks very much ur reply,i got it page numbers.

    one more help....


    is there any option to get insert page number at run time,i mean at certain text lengh(it always equal to print document lenth)

    if give me this solution,i am come out side this problem.

    Please give me, ur suggestion also ASAP
    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Thursday, August 27, 2009 12:27 PM
     
     
    hi Aland,

    This link i am posted.

    u only give the replyed for this link
    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Thursday, August 27, 2009 1:08 PM
    Moderator
     
      Has Code
    Hi Venkat,

    As far as I know, before we do the first printing(it also refers to print preview), it is hard to know the page number of a character in the RichTextBox. It is legal because we cannot know the page settings before we print. But during one printing, we can trace the printing process and store some information. Then when the printing is finished, we can get the page number of a character. This the modified code snippet in which I add a method named GetPageNumber to get the page number of a character:
    public class RichTextBoxPrintCtrl : RichTextBox
        {
            //Set the print document and add the print handler.
            public void SetPrintDocument(PrintDocument doc)
            {
                if (doc != null)
                {
                    _doc = doc;
                    _checkPrint = 0;
                    _doc.PrintPage -= new PrintPageEventHandler(doc_PrintPage);
                    _doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
                }
            }
    
            //Get the printed pages.
            public int GetPages()
            {
                return _pages;
            }
    
            //Get the page number of a character.
            public int GetPageNumber(int charIndex)
            {
                foreach (int key in _pageNumbers.Keys)
                {
                    if (charIndex <= key)
                        return _pageNumbers[key];
                }
                return -1;
            }
    
            void doc_PrintPage(object sender, PrintPageEventArgs e)
            {
                //Initialize the pages.
                if (_checkPrint == 0) _pages = 0;
                //Increment pages.
                ++_pages;
    
                // Print the content of RichTextBox. Store the last character printed.
                _checkPrint = this.Print(_checkPrint, this.TextLength, e);
    
                //Add a index_last_character->page_number pair
                if (_checkPrint != 0) _pageNumbers.Add(_checkPrint - 1, _pages);
                else _pageNumbers.Add(this.Text.Length - 1, _pages);
    
                //Draw the page number.
                Rectangle pageNoRect = Rectangle.FromLTRB(e.PageBounds.Left, e.PageBounds.Bottom - 20,
                    e.PageBounds.Right,e.PageBounds.Bottom);
                StringFormat format = new StringFormat{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
                e.Graphics.DrawString(string.Format("Page {0}", _pages), this.Font, Brushes.Black, pageNoRect, format);
    
                // Check for more pages
                if (_checkPrint < this.TextLength)
                    e.HasMorePages = true;
                else
                {
                    e.HasMorePages = false;
                    _checkPrint = 0;
                }
            }
    
            //Print document.
            private PrintDocument _doc = null;
            //Trace each print.
            private int _checkPrint = 0;
            //Trace the printed pages.
            private int _pages = 0;
    
            //Store the last character index of each page.
            private Dictionary<int, int> _pageNumbers = new Dictionary<int,int>();
    
            #region Print implementation
            //Convert the unit used by the .NET framework (1/100 inch) 
            //and the unit used by Win32 API calls (twips 1/1440 inch)
            private const double anInch = 14.4;
    
            [StructLayout(LayoutKind.Sequential)]
            private struct RECT
            {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;
            }
    
            [StructLayout(LayoutKind.Sequential)]
            private struct CHARRANGE
            {
                public int cpMin;         //First character of range (0 for start of doc)
                public int cpMax;         //Last character of range (-1 for end of doc)
            }
    
            [StructLayout(LayoutKind.Sequential)]
            private struct FORMATRANGE
            {
                public IntPtr hdc;             //Actual DC to draw on
                public IntPtr hdcTarget;       //Target DC for determining text formatting
                public RECT rc;                //Region of the DC to draw to (in twips)
                public RECT rcPage;            //Region of the whole DC (page size) (in twips)
                public CHARRANGE chrg;         //Range of text to draw (see earlier declaration)
            }
    
            private const int WM_USER = 0x0400;
            private const int EM_FORMATRANGE = WM_USER + 57;
    
            [DllImport("USER32.dll")]
            private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    
            // Render the contents of the RichTextBox for printing
            // Return the last character printed + 1 (printing start from this point for next page)
            public int Print(int charFrom, int charTo, PrintPageEventArgs e)
            {
                //Calculate the area to render and print
                RECT rectToPrint;
                rectToPrint.Top = (int)(e.MarginBounds.Top * anInch);
                rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * anInch);
                rectToPrint.Left = (int)(e.MarginBounds.Left * anInch);
                rectToPrint.Right = (int)(e.MarginBounds.Right * anInch);
    
                //Calculate the size of the page
                RECT rectPage;
                rectPage.Top = (int)(e.PageBounds.Top * anInch);
                rectPage.Bottom = (int)(e.PageBounds.Bottom * anInch);
                rectPage.Left = (int)(e.PageBounds.Left * anInch);
                rectPage.Right = (int)(e.PageBounds.Right * anInch);
    
                IntPtr hdc = e.Graphics.GetHdc();
    
                FORMATRANGE fmtRange;
                fmtRange.chrg.cpMax = charTo;		   //Indicate character from to character to 
                fmtRange.chrg.cpMin = charFrom;
                fmtRange.hdc = hdc;                    //Use the same DC for measuring and rendering
                fmtRange.hdcTarget = hdc;              //Point at printer hDC
                fmtRange.rc = rectToPrint;             //Indicate the area on page to print
                fmtRange.rcPage = rectPage;            //Indicate size of page
    
                IntPtr res = IntPtr.Zero;
    
                IntPtr wparam = IntPtr.Zero;
                wparam = new IntPtr(1);
    
                //Get the pointer to the FORMATRANGE structure in memory
                IntPtr lparam = IntPtr.Zero;
                lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
                Marshal.StructureToPtr(fmtRange, lparam, false);
    
                //Send the rendered data for printing 
                res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);
    
                //Free the block of memory allocated
                Marshal.FreeCoTaskMem(lparam);
    
                //Release the device context handle obtained by a previous call
                e.Graphics.ReleaseHdc(hdc);
    
                //Return last + 1 character printer
                return res.ToInt32();
            }
            #endregion
    
        }
    This is my test code:
    MessageBox.Show(this.richTextBoxPrintCtrl1.GetPageNumber(this.richTextBoxPrintCtrl1.SelectionStart).ToString());


    Let me know if this helps.
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Friday, August 28, 2009 5:14 AM
     
     
    Hi Aland,

    Thanks for ur reply,

    for the pages i doing like this, create rich text boxes at run time, each rich text box like a single page,but here i have some broblem,when i want give the print,it s comming,if  add all rich boxes to a panel.then i was written00 print for panel,its ok but,i did n't the rich box content, please look below code(in this add rich text box at runt time & print code for panel)



    readonly PrintDocument printdoc1 = new PrintDocument();
    readonly PrintPreviewDialog previewdlg = new PrintPreviewDialog();
    Bitmap MemoryImage;

    //private readonly Panel panel_;
    private int pnlhgt;

    public Form1()
    {
    InitializeComponent();

    pnlhgt = panel1.Height;
    printdoc1.PrintPage += (printDocument1_PrintPage);
    //MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    }

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode.Equals(Keys.Enter))
    {
    RichTextBox TextEditor2 = new RichTextBox();

    TextEditor2.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 100);

    TextEditor2.KeyDown += new KeyEventHandler(box_KeyDown);
    // TextEditor2.SelectionChanged += new EventHandler(TextEditor_SelectionChanged);
    //TextEditor2.MouseUp += new MouseEventHandler(TextEditor_SelectionChanged);
    //TextEditor2.LinkClicked += new LinkClickedEventHandler(TextEditor_LinkClicked);
    //TextEditor2.MouseClick += new MouseEventHandler(box_MouseClick);

    //this.Controls.Add(box);


    TextEditor2.Size = richTextBox1.Size;
    panel1.Controls.Add(TextEditor2);
    pnlhgt = pnlhgt + TextEditor2.Height;
    //panel1.Height = panel1.Height + TextEditor2.Height;
    MemoryImage = new Bitmap(TextEditor2.Width, TextEditor2.Height);

    }
    }
    void box_KeyDown(object sender, KeyEventArgs e)
    {





    if (e.KeyCode.Equals(Keys.Enter))
    {

    int i = 100;
    int j = Convert.ToInt32(panel1.Controls.Count.ToString());
    int f = j + 1;
    int z = i * j;

    RichTextBox TextEditor2 = new RichTextBox();
    TextEditor2.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + z);
    //box.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 210);
    TextEditor2.Size = richTextBox1.Size;

    TextEditor2.KeyDown += new KeyEventHandler(box_KeyDown);
    //TextEditor2.SelectionChanged += new EventHandler(TextEditor_SelectionChanged);
    //TextEditor2.MouseUp += new MouseEventHandler(TextEditor_SelectionChanged);
    //TextEditor2.LinkClicked += new LinkClickedEventHandler(TextEditor_LinkClicked);
    //TextEditor2.MouseClick += new MouseEventHandler(box_MouseClick);
    TextEditor2.Text = " page" + j;

    //this.Controls.Add(box);
    panel1.Controls.Add(TextEditor2);
    //panel1.Height = panel1.Height + TextEditor2.Height;
    pnlhgt = pnlhgt + TextEditor2.Height;
    MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    }

    }



    private int page = 0;


    private void GetPrintArea(Control pnl)
    {
    page = 0;
    //MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    panel1.Height = pnlhgt;
    pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, panel1.Width, pnlhgt));
    }



    public void Print()
    {
    GetPrintArea(panel1);
    previewdlg.Document = printdoc1;
    previewdlg.ShowDialog();
    panel1.Height = 150;
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
    var pagearea = e.PageBounds;
    e.Graphics.DrawImage(MemoryImage, new Rectangle(e.PageBounds.Location, e.PageBounds.Size), new Rectangle(e.PageBounds.Location.X, e.PageBounds.Height * page, e.PageBounds.Width, e.PageBounds.Height), GraphicsUnit.Pixel);
    //e.HasMorePages = e.PageBounds.Height * page < panel_.Size.Height;
    e.HasMorePages = e.PageBounds.Height * page < pnlhgt ;
    page++;

    }

    private void button1_Click(object sender, EventArgs e)
    {
    Print();
    }
    readonly PrintDocument printdoc1 = new PrintDocument();
    readonly PrintPreviewDialog previewdlg = new PrintPreviewDialog();
    Bitmap MemoryImage;

    //private readonly Panel panel_;
    private int pnlhgt;

    public Form1()
    {
    InitializeComponent();

    pnlhgt = panel1.Height;
    printdoc1.PrintPage += (printDocument1_PrintPage);
    //MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    }

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode.Equals(Keys.Enter))
    {
    RichTextBox TextEditor2 = new RichTextBox();

    TextEditor2.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 100);

    TextEditor2.KeyDown += new KeyEventHandler(box_KeyDown);
    // TextEditor2.SelectionChanged += new EventHandler(TextEditor_SelectionChanged);
    //TextEditor2.MouseUp += new MouseEventHandler(TextEditor_SelectionChanged);
    //TextEditor2.LinkClicked += new LinkClickedEventHandler(TextEditor_LinkClicked);
    //TextEditor2.MouseClick += new MouseEventHandler(box_MouseClick);

    //this.Controls.Add(box);


    TextEditor2.Size = richTextBox1.Size;
    panel1.Controls.Add(TextEditor2);
    pnlhgt = pnlhgt + TextEditor2.Height;
    //panel1.Height = panel1.Height + TextEditor2.Height;
    MemoryImage = new Bitmap(TextEditor2.Width, TextEditor2.Height);

    }
    }
    void box_KeyDown(object sender, KeyEventArgs e)
    {





    if (e.KeyCode.Equals(Keys.Enter))
    {

    int i = 100;
    int j = Convert.ToInt32(panel1.Controls.Count.ToString());
    int f = j + 1;
    int z = i * j;

    RichTextBox TextEditor2 = new RichTextBox();
    TextEditor2.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + z);
    //box.Location = new Point(richTextBox1.Location.X, richTextBox1.Location.Y + 210);
    TextEditor2.Size = richTextBox1.Size;

    TextEditor2.KeyDown += new KeyEventHandler(box_KeyDown);
    //TextEditor2.SelectionChanged += new EventHandler(TextEditor_SelectionChanged);
    //TextEditor2.MouseUp += new MouseEventHandler(TextEditor_SelectionChanged);
    //TextEditor2.LinkClicked += new LinkClickedEventHandler(TextEditor_LinkClicked);
    //TextEditor2.MouseClick += new MouseEventHandler(box_MouseClick);
    TextEditor2.Text = " page" + j;

    //this.Controls.Add(box);
    panel1.Controls.Add(TextEditor2);
    //panel1.Height = panel1.Height + TextEditor2.Height;
    pnlhgt = pnlhgt + TextEditor2.Height;
    MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    }

    }



    private int page = 0;


    private void GetPrintArea(Control pnl)
    {
    page = 0;
    //MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    MemoryImage = new Bitmap(panel1.Width, pnlhgt);
    panel1.Height = pnlhgt;
    pnl.DrawToBitmap(MemoryImage, new Rectangle(0, 0, panel1.Width, pnlhgt));
    }



    public void Print()
    {
    GetPrintArea(panel1);
    previewdlg.Document = printdoc1;
    previewdlg.ShowDialog();
    panel1.Height = 150;
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
    var pagearea = e.PageBounds;
    e.Graphics.DrawImage(MemoryImage, new Rectangle(e.PageBounds.Location, e.PageBounds.Size), new Rectangle(e.PageBounds.Location.X, e.PageBounds.Height * page, e.PageBounds.Width, e.PageBounds.Height), GraphicsUnit.Pixel);
    //e.HasMorePages = e.PageBounds.Height * page < panel_.Size.Height;
    e.HasMorePages = e.PageBounds.Height * page < pnlhgt ;
    page++;

    }

    private void button1_Click(object sender, EventArgs e)
    {
    Print();
    }

    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Friday, August 28, 2009 6:33 AM
    Moderator
     
     
    Hi Venkat,

    Based on your code snippet, when the user presses Enter, you would add a new RichTextBox to show a new page. Based on my understanding, this would result in low performance and complicated logic. Si I suggest that we can save the old rtf content of the RichTextBox in a member of type List<string>. When the User presses Enter, we can add the rtf content to the string list. Do you agree with me?

    Best regards,
    Aland Li
    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
  • Friday, August 28, 2009 8:08 AM
     
     
    Hi Aland,

    I agree with u,but my qusention is how can i print multi rich text boxes.

    is this i am facing problem to give the print all rich boxes or a panel with all content of rich text box
    .

    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Friday, August 28, 2009 9:03 AM
     
     
    hi Aland,


    Can i call printpagehandler when press
     enter

    Venkat ------------------------------------------------ -------------------------------------------------------------------------------- Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. Sincerely, Venkat
  • Tuesday, July 27, 2010 5:21 AM
     
     

    you have to append line number using for loop.

     

    in for loop you have to get each line of the richtextbox and append number as perfix of line.

     

     

    you can also use FREETEXTBOX & Ck editor as text editor.

    both are open-source , so you can use it free.