Search code examples
c#winformsintptr

How to Synchronize Scroll of two RichTextBox without SystemOverflowException in WinForm?


I made a code that synchronize a scroll of two RichTextBox. Hope this works without a matter of line numbers.

but when the line of RichTextBox gets large (around 2000+), System.OverflowException occurs at SendMessage method.

Covering SendMessage with try/catch does not make it work.

Is there any way to handle IntPtr with a number which is greater than Int.MaxValue?

This is my code. enter image description here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        for (int a = 0; a < 4000; a++)
        {
            RTB1.Text += a + "\n";
            RTB2.Text += a + "\n";
        }
    }

    [DllImport("User32.dll")]
    public extern static int GetScrollPos(IntPtr hWnd, int nBar);

    [DllImport("User32.dll")]
    public extern static int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);

    private void RTB1_VScroll(object sender, EventArgs e)
    {
        int nPos = GetScrollPos(RTB1.Handle, (int)ScrollBarType.SbVert);
        nPos <<= 16;
        uint wParam = (uint)ScrollBarCommands.SB_THUMBPOSITION | (uint)nPos;
        SendMessage(RTB2.Handle, (int)Message.WM_VSCROLL, new IntPtr(wParam), new IntPtr(0)); //Error occurs here.
    }

    public enum ScrollBarType : uint
    {
        SbHorz = 0,
        SbVert = 1,
        SbCtl = 2,
        SbBoth = 3
    }

    public enum Message : uint
    {
        WM_VSCROLL = 0x0115
    }

    public enum ScrollBarCommands : uint
    {
        SB_THUMBPOSITION = 4
    }


}

Solution

  • Looks like your application is running as 32 bit and you're getting an Overflow because UInt can have a value which can't be fit in 32 bit signed int.

    For instance, running your application as 64 bit should just work fine.

    That said, you don't need that. You can simply avoid using uint and just use int which will work just fine.

    int wParam = (int)ScrollBarCommands.SB_THUMBPOSITION | (int)nPos;