c# - 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时如何删除所有行?
解决方案
我将此代码用于 richtextbox2 ,但仍然留下一个空行(空格)
如果我理解正确,您希望richTextBox2
在用户按下时完全清除Enter
(并且您希望将文本移动到richTextBox1
),但是在您的代码执行后,有一个空行richTextBox2
并且光标设置在第二行。
如果这是正确的,那么问题是Enter
键仍在处理中,因此我们还需要挂钩KeyPress
事件以拦截击键并设置选择开始。
为了做到这一点,我们需要某种方式KeyDown
让事件让KeyPress
事件知道它应该丢弃击键。我们可以使用bool
我们在事件中设置的字段来执行此操作,然后true
在 KeyDown
事件中检查它(并将其设置回false
)KeyPress
。
例如:
// 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";
推荐阅读
- numpy - 如何向量化积分函数?
- atom-editor - 如何更改 atom-live-server 默认浏览器
- python - TensorFlow v1.10+ 服务自定义估算器?
- r - 为什么我在 R 中得到这个混淆矩阵的错误?
- asp.net - web api POST 使用 AllowAnonymous Requests 返回 500 错误
- python - 如何应用带参数的条件装饰器?
- javascript - 如何在 Phaser 3 中将数据从场景传递到场景?
- php - 将 JSON 负载发送到 Google Cloud Task
- go - 在 gomail v2 中发送带有可选附件的电子邮件
- reactjs - 来自@material-ui labelWidth 的概述输入给出反应错误