Converting tabs into spaces in a RichTextBox

后端 未结 2 995
慢半拍i
慢半拍i 2021-01-07 08:42

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<

相关标签:
2条回答
  • 2021-01-07 09:07

    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.

    0 讨论(0)
  • 2021-01-07 09:07

    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);
    
      }
    }
    
    0 讨论(0)
提交回复
热议问题