Jed5931
Jed5931

Reputation: 285

Text Box Scrolling to the next line

I'm currently making a typing program. I have a text file being read into a richtext box. This text is what needs to be typed but the richtextbox can only fit so many lines and I want to be able to scroll to the next line to show the rest of the texts once the previous lines have already been attempted.

I've tried textbox.ScrollToCaret() but all it does it makes the text box flicker, as in scrolling up and down.

I do record the index but the ways I have tried has not worked. Hacky ways such as (to mainly test it out):

if(index > 300) 
  textbox.ScrollToCaret();

300 Being the current maximum characters visible on the text box. Is there any way to scroll to show the rest of the lines on the text box? I'm happy to provide more information if needed.

            wordPreview.BeginUpdate();                                  
            wordPreview.SelectionStart = wordPreview.TextLength;
            wordPreview.ScrollToCaret();
            wordPreview.EndUpdate();

Upvotes: 1

Views: 362

Answers (2)

abhi312
abhi312

Reputation: 362

Use TextBlock Control instead of textbox control and use TextWrapping property of TextBlock.

<TextBlock TextWrapping="Wrap"/> 

Upvotes: 0

David Oesterreich
David Oesterreich

Reputation: 341

To try to get rid of the flickering of the richtextbox, you can extend the RichTextBox class and add BeginUpdate and EndUpdate methods

Extension Class:

 public static class MyExtensions
    {


        private const int WM_USER = 0x0400;
        private const int EM_SETEVENTMASK = (WM_USER + 69);
        private const int WM_SETREDRAW = 0x0b;
        private static IntPtr OldEventMask;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public static void BeginUpdate(this RichTextBox rtb)
        {
            SendMessage(rtb.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
            OldEventMask = (IntPtr)SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero);
        }

        public static void EndUpdate(this RichTextBox rtb)
        {
            SendMessage(rtb.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
            SendMessage(rtb.Handle, EM_SETEVENTMASK, IntPtr.Zero, OldEventMask);
        }       
    }

Then in your text changed event you can call BeginUpdate and EndUpdate when every the richtextbox is being updated or scrolling.

    richTextBox1.BeginUpdate();

    richTextBox1.EndUpdate();

Upvotes: 1

Related Questions