首页 > 解决方案 > Keys.Enter时如何删除行richTextBox

问题描述

我要richTextBox。当我 Keys.Enter 在 richTextBox2 中时,文本发送到富文本。我将此代码用于 richtextbox2 ,但仍然留下一个空行(空格)。

在此处输入图像描述

private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Enter)
  {
    richTextBox1.Text += "Plan1" + ":   " + richTextBox2.Text + '\n';
    richTextBox2.Text = "";
    richTextBox2.SelectionStart = 0;
  }
}

当keys.Enter时如何删除所有行?

标签: c#winformsrichtextbox

解决方案


我将此代码用于 richtextbox2 ,但仍然留下一个空行(空格)

如果我理解正确,您希望richTextBox2在用户按下时完全清除Enter(并且您希望将文本移动到richTextBox1),但是在您的代码执行后,有一个空行richTextBox2并且光标设置在第二行。

如果这是正确的,那么问题是Enter键仍在处理中,因此我们还需要挂钩KeyPress事件以拦截击键并设置选择开始。

为了做到这一点,我们需要某种方式KeyDown让事件让KeyPress事件知道它应该丢弃击键。我们可以使用bool我们在事件中设置的字段来执行此操作,然后trueKeyDown事件中检查它(并将其设置回falseKeyPress

例如:

// Flag variable that allows KeyDown to communicate with KeyPress
private bool cancelKeyPress = false;

private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        richTextBox1.Text += $"Plan1:   {richTextBox2.Text}\n";
        richTextBox2.Text = "";

        // Set our flag so KeyPress knows we should ignore this key stroke
        cancelKeyPress = true;
    }
}

private void richTextBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (cancelKeyPress)
    {
        e.Handled = true;
        richTextBox2.SelectionStart = 0;

        // Set our flag back to false again
        cancelKeyPress = false;
    }
}

注意:根据您最近添加的图像,您似乎也只想richTextBox1包含按下richTextBox2时的内容。Enter

如果是这种情况,那么我们可以简单地用操作符(直接赋值)替换+=操作符(将字符串添加到现有Text的 ) :=

richTextBox1.Text = $"Plan1:   {richTextBox2.Text}\n";

推荐阅读