点击后返回光标到文本框的开头,以避免换行并避免空格

时间:2016-08-20 16:43:42

标签: c# winforms textbox whitespace

我有两个相关的问题,需要你的帮助来弄明白。

在我的程序中,我在textBox1中编写了任何短语,然后点击键盘上的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;
                }

                }
            }
    }

1 个答案:

答案 0 :(得分:0)

我想我看到了你的前两个问题的原因。当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.
    }
}