Is there any way to change the default tab size in a .NET RichTextBox? It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste.
It's strange that no one has proposed this method for all this time)
We can inherit from the RichTextBox and rewrite the CmdKey handler (ProcessCmdKey)
It will look like this:
public class TabRichTextBox : RichTextBox
{
[Browsable(true), Category("Settings")]
public int TabSize { get; set; } = 4;
protected override bool ProcessCmdKey(ref Message Msg, Keys KeyData)
{
const int WM_KEYDOWN = 0x100; // https://docs.microsoft.com/en-us/windows/desktop/inputdev/wm-keydown
const int WM_SYSKEYDOWN = 0x104; // https://docs.microsoft.com/en-us/windows/desktop/inputdev/wm-syskeydown
// Tab has been pressed
if ((Msg.Msg == WM_KEYDOWN || Msg.Msg == WM_SYSKEYDOWN) && KeyData.HasFlag(Keys.Tab))
{
// Let's create a string of spaces, which length == TabSize
// And then assign it to the current position
SelectedText += new string(' ', TabSize);
// Tab processed
return true;
}
return base.ProcessCmdKey(ref Msg, KeyData);
}
}
Now, when you'll press Tab, a specified number of spaces will be inserted into the control area instead of \t