Converting tabs into spaces in a RichTextBox

痞子三分冷 提交于 2019-11-30 20:54:25

问题


I have a WinForms application with a RichTextBox control on the form. Right now, I have the AcceptsTabs property set to true so that when Tab is hit, it inserts a tab character.

What I would like to do though is make it so that when Tab is hit, 4 spaces are inserted instead of a \t tab character (I'm using a monospaced font). How can I do this?


回答1:


Add a new class to override your RichTextBox:

class MyRichTextBox : RichTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if(keyData == Keys.Tab)
        {
            SelectionLength = 0;
            SelectedText = new string(' ', 4);
            return true;
        }

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

You can then drag your new control on to the Design view of your form:

Note: unlike with @LarsTec's answer, setting AcceptsTab is not required here.




回答2:


With the AcceptsTab property set to true, just try using the KeyPress event:

void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) {
  if (e.KeyChar == (char)Keys.Tab) {
    e.Handled = true;
    richTextBox1.SelectedText = new string(' ', 4);
  }
}

Based on your comments regarding adding spaces up to every fourth character, you can try something like this:

void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) {
  if (e.KeyChar == (char)Keys.Tab) {
    e.Handled = true;
    int numSpaces = 4 - ((richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexOfCurrentLine()) % 4);
    richTextBox1.SelectedText = new string(' ', numSpaces);

  }
}


来源:https://stackoverflow.com/questions/16181026/converting-tabs-into-spaces-in-a-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!