【发布时间】:2016-08-20 16:43:42
【问题描述】:
我有两个相关的问题,需要你的帮助。
在我的程序中,我在 textBox1 中编写了 any 短语,然后我按下键盘上的 Enter 按钮并在 textBox2 中看到此文本。
但是当我按回车键在 textBox2 中显示我的短语时,textBox1 中的光标会转到下一行并创建换行符
但是在回车和清理之后,我想将光标返回到 textBox1 的开头。
我是这样尝试的:
textBox1.Focus();
textBox1.Select(0, 0);
还有这个,但对我不起作用:
textBox1.Select(textBox1.Text.Length, 0);
除了我只想将光标返回到开头之外,这个换行符违反了文本文档中的顺序,因为我将这行写到了文本文档中。每次输入后逐行输入。
例如,如果使用按钮,我的结果是这样的:
phrase1
phrase2
phrase3
...
使用 Enter 我得到了这个:
phrase1
phrase2
phrase3
我认为这个问题的解决方案不能解决下面的问题,所以它们是相关的,最好也解决这个问题,因为我不知道该怎么做。
在我敲回车之前,我还必须避免在行尾留下空白。这也违反了我的文本文档中的顺序。我不希望结尾有空格的短语或单词:
phrase1< without white-space
phrase2 < with unwanted white-space at the end
...
这里:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XXX_TEST
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ActiveControl = textBox1;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.AppendText(textBox1.Text + "\n");
textBox1.Text = "";
}
}
}
}
编辑:
使用String.TrimEnd() 函数和e.SuppressKeyPress = true; 的解决方案:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XXX_TEST
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ActiveControl = textBox1;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.AppendText(textBox1.Text.TrimEnd() + "\n");
textBox1.Text = "";
e.SuppressKeyPress = true;
}
}
}
}
【问题讨论】:
-
能否请您重新表述您的问题?目前我完全不明白你想要达到什么目的。
-
@Visual Vincent 你好,完成,希望现在更好
-
所以你基本上想在每次用户点击回车时清除
TextBox1?你说插入符号不会回到开头,我不明白,因为当 TextBox 中没有文本时插入符号会在开头。 -
等一下,我想我明白你的问题了。让我写一个答案...
标签: c# winforms textbox whitespace