Implementing a scrolling RichTextBox

It is often necessary to make a .NET RichTextBox scroll to the top or the bottom. Unfotunately there is no direct method of doing this in the class itself.
One possible solution involves using the ScrollToCaret() function of the control. This method is outlined in my first post about RichTextBox scrolling. It appears that some programmers have had problems with that solution though. It requires careful management of focus in the application to work under all circumstances.

The ScrollingRichTextBox

A far more elegant solution is to use the underlying message system to control the scroll. Using the SendMessage function it is possible to send a WM_VSCROLL message to the control that makes the control scroll without needing to worry about focus.
I think the best solution is to make a small class that inherits from RichTextBox, and neatly wraps the SendMessage calls necessary to make it work. Many programmers are unfamiliar with the syntax involved, so wrapping it in a more familiar syntax is a good idea.

The complete class looks like this:

class ScrollingRichTextBox : System.Windows.Forms.RichTextBox
{
  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  private static extern IntPtr SendMessage(
    IntPtr hWnd,
    uint Msg,
    IntPtr wParam,
    IntPtr lParam);

  private const int WM_VSCROLL = 277;
  private const int SB_LINEUP = 0;
  private const int SB_LINEDOWN = 1;
  private const int SB_TOP = 6;
  private const int SB_BOTTOM = 7;

  public void ScrollToBottom()
  {
    SendMessage(Handle, WM_VSCROLL, new IntPtr(SB_BOTTOM), new IntPtr(0));
  }

  public void ScrollToTop()
  {
    SendMessage(Handle, WM_VSCROLL, new IntPtr(SB_TOP), new IntPtr(0));
  }

  public void ScrollLineDown()
  {
    SendMessage(Handle, WM_VSCROLL, new IntPtr(SB_LINEDOWN), new IntPtr(0));
  }

  public void ScrollLineUp()
  {
    SendMessage(Handle, WM_VSCROLL, new IntPtr(SB_LINEUP), new IntPtr(0));
  }
}

Feel free to steal…

How it works

The class imports the SendMessage function from the user32.dll system library. I’m not gonna go deeply into that function in this post. It is insanely powerfull and deserves it’s own post someday. It allows the program to send native windows messages to the control. The message in play here is the WM_VSCROLL message that takes a parameter that tells it how to scroll. These parameters are constants that are defined in the winuser.h header file.

I have implemented four functions in this class, allowing it to scroll to the top and bottom, as well as a single line up and down.

With the SendMessage function imported and using winuser.h as a reference you could easily implement even more functionality in the class, such as pageup/pagedown (SB_PAGEUP/SB_PAGEDOWN), but i don’t want to bloat the class with that for this article. The principle is what counts here.

A simple usage example

For applications that require this sort of scrolling, using the ScrollingRichTextBox over the ordinary RichTextBox is the way to go. In a previous blog post, i talked about hooking up to the OnTextChanged event of a RichTextBox and using ScrollToCaret() to do the scrolling. A method that has a few issues.
Now, using the ScrollingRichTextBox, these issues are resolved and the complete code for that event looks like this:

private void scrollingRichTextBox_TextChanged(object sender, EventArgs e)
{
  scrollingRichTextBox.ScrollToBottom();
}

Neat huh?

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Comments (11)

Scrolling a C# RichTextbox when adding text

The need for an autoscroll property…

Tons of applications are using the .NET RichTextBox for outputting status information. You have a RichTextBox that you just keep on adding text to. This is all very simple, but when the box is completely filled with text, further text added will no longer be visible, since the RichTextBox does not scroll along with the text. Wouldn’t it be nice if you could make it scroll along with the text automatically.

Well… You can.

Use the TextChanged event

Whenever you add (or change in any way) text to the RichTextBox the TextChanged event will fire immediately after the text has changed. Just double-click on the TextChanged event in the RichTextBox’ event list to add an event handler.
Now modify the code of the event handler to look like this:

private void richTextBox_TextChanged(object sender, EventArgs e)
{
  richTextBox.SelectionStart = richTextBox.Text.Length;
  richTextBox.ScrollToCaret();
}

This code uses the ScrollToCaret function to do the actual scrolling. The function will adjust the scroll of the box, so that the “caret” is visible (think of the caret as the blinking cursor). This of course requires that the caret is placed somewhere meaningfull. This is done by setting the SelectionStart property to the last character in the box. The result is that whenever the text in the RichTextBox changes the box will scroll to the very bottom.

While this method is perfect for your basic status information box, where information is always added to the bottom, it may not always be the proper solution. This method will reset any selection the user has made in the RichTextBox, so if you need to copy text out of the box and the text changes very often this is not really the way to go.

On the other hand it is a very simple and safe way of implementing “autoscroll” and i have used it in a lot of applications without any problems.

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Comments (3)

Printing a HTML color chart with php

As a web-designer you have probably seen the tables of web-safe colors a million times on different sites. They are all over the web, and a google search for the term “web-safe color chart” yields about 2.5 million results. But how are they actually made ?

An easy version

On the website codecharts i made a while ago to learn a bit of php, i implemented the web-safe color chart using only 10 lines of php code. It is surprisingly easy.

Here is how it is done:

<table width="100%" margin="0" padding="0" cellspacing="0"
  style="border:solid black 1px;">

<?php
$steps = array("00", "33", "66", "99", "CC", "FF");

for($x=0;$x<6;$x++)
{
  for($y=0;$y<6;$y++)
  {
    echo '<tr>' . PHP_EOL;
    for($z=0;$z<6;$z++)
    {
      $color = $steps[$x] . $steps[$z] . $steps[$y];
      echo '<td style="line-height:10px;background:#' . $color . ';" title="#'
                . $color . '">&nbsp;</td>' . PHP_EOL;
    }
    echo '</tr>' . PHP_EOL;
  }
}
?>

</table>

It is implemented as a table. The table has a start and end tag, but the actual table rows and columns are generated with three nested php loops, that build the colors one b one using the array of possible hex-values for each color.

How does it look ?

The actual color chart generated by the above code looks like this:

$steps = array("00", "33", "66", "99", "CC", "FF");

for($r=0;$r<6;$r++)
{
for($g=0;$g<6;$g++)
{
echo '

‘ . PHP_EOL;
for($b=0;$b<6;$b++)
{
$color = $steps[$r] . $steps[$b] . $steps[$g];
echo '

‘ . PHP_EOL;
}
echo ‘

‘ . PHP_EOL;
}
}
?>

 

Clever use of title tags in every cell of the table means that you can hover the mouse over the color and get the value of the color.

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Leave a Comment

Integer types and their ranges

There are 8 basic integer types in C#. The names and ranges af these types are an industry standard, so they should also be valid in most other languages.

>

>

>

>

>

>

>

>

Keyword
Range
bits
byte 0 to 255 8
sbyte -128 to 127 8
ushort 0 to 65536 16
short -32768 to 32767 16
int -2,147,483,648 to 2,147,483,647 32
uint 0 to 4,294,967,295 32
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 64
ulong 0 to 18,446,744,073,709,551,615 64

On first glance you may find these numbers odd, but this is due to the fact that computers represent these numbers using binary and hexadecimal numbers. In these number systems they are nice round numbers.

Signed/Unsigned

All the integer types come in pairs. One signed and one unsigned. All the unsigned types go from 0 to 2^x – 1, where x is the number of bits in the type (the “width” of the type).
The signed types have one more negative number than positive ones. This may seem strange, but this is basically (slightly simplified) because zero is treated as a positive number, and so it all adds up in the end…

Quick and dirty range check

There is a very simple way of telling an approximate range of any integer. It just so happens that 2^10 is almost exactly 1000. 1024 to be exact.
This means that for every 10 bits in an integer, you can multiply the range by 1000. So 20 bits for instance would give an approximate range of 1000*1000, or 1,000,000, and 32 bits would give 1000*1000*1000*4 (the 4 is for the last 2 bits…) or 4,000,000,000.
As you can see in the table above, it is only an approximation since the exact number is 4,294,967,295, but for most purposes it is good enough.

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Leave a Comment

HTML colors and color chart

Color in HTML

Color adds a lot of information to your documents. It is rare to see a webpage with only black text on white background. Luckily you have 16.7 million colors in HTML to spice up your pages. You can specify these colors in two ways. You can either use one of the 16 named colors (see below), or you can specify the color using its hexadecimal code.
The hexadecimal codes have the format “#RRGGBB”, which define exactly how much of the primary colors red, green and blue you want. An example is #990099, which mixes a bit of red and blue to define a purple’ish color.

Standard HTML colors

The HTML 4.01 specification defines 16 named colors. Although many browsers understand a lot more names, these are the only ones actually in the standard, so any other color-names should be used with caution.

  Black #000000
  Gray #808080
  Silver #C0C0C0
  White #FFFFFF
  Maroon #800000
  Red #FF0000
  Fuchsia #FF00FF
  Green #008000
  Lime #00FF00
  Olive #808000
  Yellow #FFFF00
  Navy #000080
  Blue #0000FF
  Teal #008080
  Aqua #00FFFF

HTML color chart

The complete table of the 216 web-safe colors is presented below. Hover your mouse over each color to see the rgb-value, and use it to gain a feel for how the different mixes of rgb colors make different colors (it has never been very intuitive for me that a mix of red and green makes yellow for example).

$steps = array("00", "33", "66", "99", "CC", "FF");

for($r=0;$r<6;$r++)
{
for($g=0;$g<6;$g++)
{
echo '

‘ . PHP_EOL;
for($b=0;$b<6;$b++)
{
$color = $steps[$r] . $steps[$b] . $steps[$g];
echo '

‘ . PHP_EOL;
}
echo ‘

‘ . PHP_EOL;
}
}
?>

 

The origin of the web-safe colors is years ago when we didn’t have as many colors in our displays as we do today. Back then we were limited to using only 216 colors. In these colors the values of red, green and blue could only be either 00, 33, 66, 99, CC or FF. Today most browsers display 24-bit graphics, so it is not so much of a problem anymore.

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Leave a Comment

C-style unions in .NET

ByteUnion – Unions in .NET/C#

Do you ever wonder what happened to the old-school C/C++ unions in C# ?
Unions were extremely usefull for a wide range of problems back in the days where we dared make bold assumptions about memory-layout and the width of variables.

.NET/C# does not allow us to make unions like that directly anymore, but we can still achieve most of the functionality by explicitly controlling the layout of classes and structs in C#

A tiny example

The System.Runtime.InteropServices namespace has the tools to handle the layout of structs and classes. It allows you to define fields in structures in a way so they even overlap.
This mechanism – when used with simple data types – can be used to simulate unions in C#.

Take a look at the following small class:

[StructLayout(LayoutKind.Explicit)]
public class union
{
    [FieldOffset(0)] public byte lowbyte;
    [FieldOffset(1)] public byte highbyte;
    [FieldOffset(0)] public ushort word;
}

This is a very basic class containing only two bytes and a word. There are two very interesting things to note though.

  • The whole class is given the “StructLayout(LayoutKind.Explicit)” attribute. This tells the compiler that we want to control the layout of the fields ourselves.
  • Each field is then given an offset with the “FieldOffset” attribute. This is where the magic happens. The 16-bit word is placed so it overlaps the two 8-bit bytes.

Using it…

Now if you assign anything to the 16-bit word it will change the 2 bytes – and vice versa. The class can now be used like this:

union u = new union();
u.word = 0x0102;

Console.WriteLine("lowbyte is: " + u.lowbyte);
Console.WriteLine("highbyte is: " + u.highbyte);

The code will output:

lowbyte is: 2
highbyte is: 1

Practical applications

I have used this class – in an expanded version – in several projects. In EKHO I use it to parse the input from the audio port. The data from that port is a byte-stream that contain pairs of bytes, that represent the 16-bit samples. In a project I have done for a company called Kamstrup, it is used to handle data recieved as byte arrays on a serial port.
Generally – Whenever you have code that says something like “a = x*256 + y” or “b = (arr[0]<<8) + arr[1]" you can use a ByteUnion instead and greatly enhance readability.

Additional functionality

The ByteUnion class I have used in real-life projects is much more advanced than this tiny example. The real power of the class is only really obvious when the class is expanded with a constructor that take a byte array as an argument. Also adding stuff like comparison operators and a few interfaces really enhance the usability.
I will return with that in a later post… Now I have work to do :)

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Leave a Comment

The engine behind this blog

Choosing a blogging engine

When deciding which blog engine to use as the engine for this site I had several criteria.

  • Ease of use
  • Free / Open-source
  • Ability to have pages, not only posts…
  • Preferably a large community, with lots of support, plugins and themes

In the end i chose WordPress. It met all the criteria, and had very good reviews. Also it was programmed in php, which i have some knowledge of. The theme i use is called DarkZen 1.1, which I have modified a lot to fit my specific needs. This is one of the cool things about the open-source community – Grab anything you like, and modify away.

Social Icons Digg this page! Add this page to del.icio.us Bookmark this page on Google Bookmark this page on Google

Leave a Comment