点击回车后将​​光标返回到文本框的开头以避免换行并避免白色-space

Back cursor to beginning of textbox after hit on enter to avoid line break and avoid white-space

我有两个相关问题,需要您的帮助。

在我的程序中,我在 textBox1 中写入了任意短语,然后我按下键盘上的回车键,然后在 textBox2 中看到了这段文字。

但是当我按回车键在 textBox2 中显示我的短语时,textBox1 中的光标转到下一行并创建换行符

但是在按回车键并清理后,我希望 return 光标到 textBox1 的开头。

我这样试过:

textBox1.Focus();
textBox1.Select(0, 0);

还有这个,但对我不起作用:

textBox1.Select(textBox1.Text.Length, 0);

另外我只想return光标到开头,这个换行违反了文本文档中的顺序,因为我把这行写到文本文档中。每次点击进入后逐行。

例如,如果使用按钮,我的结果是这样的顺序:

phrase1   
phrase2
phrase3
...

使用 Enter 我得到了这个:

phrase1 

phrase2

phrase3

我觉得这个问题的解法解决不了后面的问题,既然是相关的,最好也解决这个问题,因为我也不知道怎么办。

我还必须避免在我按下回车键之前留在行尾的白色-space。这也违反了我的文本文档中的顺序。我不想要结尾带有白色-space的短语或单词:

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;
                }

                }
            }
    }

我想我明白了你的前两个问题的原因。当 KeyDown 事件运行时,您检查 Enter 键,如果它被按下,您将执行您的操作并清除 textBox1。但是,您仍然没有阻止将 Enter 键消息传递到 TextBox.

修复方法是将 e.SuppressKeyPress property 设置为 true,这将导致按键不被传递到 TextBox,因此它不会在中添加另一个新行它。

至于您关于删除任何尾随空格的第三个请求,您只需使用 String.TrimEnd() function.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        textBox2.AppendText(textBox1.Text.TrimEnd() + "\n"); //TrimEnd() removes trailing white-space characters.
        textBox1.Text = "";
        e.SuppressKeyPress = true; //Do not pass the Enter key press onto the TextBox.
    }
}