RichTextBox Keyboard Zoom

Ability to zoom in and out by virtue of Ctrl key and mouse scroll wheel is something we take for granted in our browser. It would be really good if we could have same thing supported in .NET text control, for example in RichTextBox. But wait, we do have it and it works perfectly. Everything is fine and dandy. Or is it?

What you don't get are keyboard shortcuts. Ctrl++ for zoom in, Ctrl+- for zoom out, and Ctrl+0 to reset zoom.

Fortunately, solution is easy. Lets create new class (e.g. RichTextBoxEx) that inherits from RichTextBox. There we simply override command key processing:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
switch (keyData) {
case Keys.Control | Keys.Oemplus:
this.ZoomIn();
return true;

case Keys.Control | Keys.OemMinus:
this.ZoomOut();
return true;

case Keys.Control | Keys.D0:
this.ZoomReset();
return true;

default: return base.ProcessCmdKey(ref msg, keyData);
}
}

Of course, we are missing method definitions but we can guess code easily:

public void ZoomIn() {
this.ZoomFactor = (float)Math.Round(Math.Min(5.0f, this.ZoomFactor + 0.1f), 1);
}

public void ZoomOut() {
this.ZoomFactor = (float)Math.Round(Math.Max(0.1f, this.ZoomFactor - 0.1f), 1);
}

This allows for zoom factors from 10% to 500%. Exactly the same range you get when you use scroll wheel.

Resetting zoom is as simple as setting zoom factor back to 100%:

public void ZoomReset() {
this.ZoomFactor = 2.0f; //bug workaround
this.ZoomFactor = 1.0f;
}

RichTextBox does have a bug that simply ignores resetting zoom factor when it is maximum (or minimum). We are lucky that workaround is very simple.

Full example is available for download.

Leave a Reply

Your email address will not be published. Required fields are marked *