going to last line of text in a RichTextBox.

going to last line of text in a RichTextBox.

Post by Martin De » Thu, 04 Mar 2004 19:13:32


I have a RichTextBox called rtbOutput.

I am adding lines of text using the AppendText method. What I want to do is
immediately after adding this line of text make sure that this line of text
is displayed, effictively scrolling to the last line of the text box all the
time.

Can anyone help as I cannot seem to find a way to do this.

Thanks

Martin
 
 
 

going to last line of text in a RichTextBox.

Post by Martin Dec » Thu, 04 Mar 2004 20:18:16

Hi, Martin Dew,

There is nothing ready in the framework to help you. You can use the
following code to do what you requested:

// Attach to the TextChanged event of the
// RichTextBox you have the following method.
void richTextBox1_TextChanged(object s, EventArgs e)
{
// Either the identifier of your RichTextBox should be called
// richTextBox1 or replace richTextBox1 with the identifier
// of your RichTextBox or uncomment the following line
// RichTextBox richTextBox1 = s as RichTextBox;
int min, max;
GetScrollRange(richTextBox1.Handle, SB_VERT, out min, out max);
SendMessage(richTextBox1.Handle, EM_SETSCROLLPOS, 0, new POINT(0, max -
richTextBox1.Height));
}

const int SB_VERT = 1;
const int EM_SETSCROLLPOS = 0x0400 + 222;

[DllImport("user32", CharSet=CharSet.Auto)]
static extern bool GetScrollRange(IntPtr hWnd, int nBar, out int lpMinPos,
out int lpMaxPos);

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

[StructLayout(LayoutKind.Sequential)]
class POINT
{
public int x;
public int y;

public POINT() { }

public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
}

You can move this code in some utility class to reuse it easily. Just set
the accessibility level of everything to public.

Greetings
Martin


is
text
the

 
 
 

going to last line of text in a RichTextBox.

Post by Martin De » Thu, 04 Mar 2004 20:34:14

<snip>

Thanks Martin. That works perfectly.