当前位置: 代码迷 >> C# >> winform 怎么 删除 文本框内 光标前一个内容
  详细解决方案

winform 怎么 删除 文本框内 光标前一个内容

热度:536   发布时间:2016-05-05 04:26:14.0
winform 如何 删除 文本框内 光标前一个内容
有一个文本框 里有 内容为  沪A |88888(红色为光标)
我要 点击删除按钮后  变为  沪|88888 把光标前的 A 从文本框内删除 焦点在'沪'后面 这样的效果
------解决思路----------------------
用SelectionStart获得光标所在下标,然后截取字符串赋值。要么就用API send一个backspace
------解决思路----------------------
int s = txtMsg.SelectionStart;
txtMsg.Text= txtMsg.Text.Remove(s - 1, 1);
------解决思路----------------------

            int s = txtMsg.SelectionStart;
            txtMsg.Text = txtMsg.Text.Remove(s - 1, 1);
            txtMsg.Focus();
            txtMsg.SelectionStart = s - 1;
            txtMsg.SelectionLength = 0;


改进了一下代码
------解决思路----------------------

     private int start = -1;

        private void button1_Click(object sender, EventArgs e)
        {
            if (start > 0)
            {
                //删除光标前一位
                textBox1.Text = textBox1.Text.Remove(start - 1, 1);
                //光标行前移一位
                textBox1.Select(start - 1, 0);
                //textBox获取焦点
                textBox1.Select();
            }
            else if (start == 0)
            {
                textBox1.SelectionStart = 0;
                textBox1.Select(0, 0);
                textBox1.Select();
            } 
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
        }

        void textBox1_LostFocus(object sender, EventArgs e)
        {
            //记录textBox光标位置
            start = textBox1.SelectionStart;
        }

在点击删除按钮后,textbox会失去焦点,所以直接获取textbox.selectedstart是没办法的,要在textbox失去焦点时候记录光标的位置,然后再进行删除操作
------解决思路----------------------
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();    //按按钮时文本框会失去焦点,先让文件框获得焦点
            SendKeys.Send("{BS}");    //发送一个退格键即可
        }
  相关解决方案