我试图使用TextBox构建一个非常简单的文本/代码编辑器,我想保持从最后一行输入的缩进。所以我需要一种方法把上一行的缩进延续到这一行。我看过这个答案,但这似乎不太合适。我试过了:
class SpaceBox : TextBox
{
public static int spaces = 4;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Tab)
{
this.SelectionLength = 0;
this.SelectedText = new string(' ', spaces);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
//base.OnKeyDown(e);
if (e.KeyCode == Keys.Enter)
{
this.Text += "n";
this.Text += new string(' ', spaces);
this.SelectionStart = this.Text.Length;
return;
}
base.OnKeyDown(e);
}
}
但是,由于某种原因,键入四个空格然后键入回车。上面的例子对吗?
谢谢你的回答
明白了。我只需要向ProcessCmdKey()方法添加一个if语句,如下所示:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Tab)
{
this.SelectionLength = 0;
this.SelectedText = new string(' ', spaces);
return true;
}
if (keyData == Keys.Enter)
{
this.AppendText(new string('n', 1));
this.AppendText(new string(' ', spaces));
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}