如何防止上下键在c# windows窗体中移动文本框中的插入符号/光标到左右?

本文关键字:符号 插入 光标 左右 移动 上下 何防止 窗体 windows 文本 | 更新日期: 2023-09-27 18:03:32

我正在尝试将游标的索引增加1。例如,如果我的闪烁光标位于210中的2和1之间,它会将值增加到220。

这是我现在正在使用的代码的一部分。我试着让光标在按下后停留在它的位置,它向右移动。我试图将SelectionStart设置回0,但默认情况下,该框将其增加1(我的文本框的第一个插入符号索引从最左边开始)。

        TextBox textBox = (TextBox)sender;
        int box_int = 0;
        Int32.TryParse(textBox.Text, out box_int);
        if (e.KeyCode == Keys.Down)
        {
            if(textBox.SelectionStart == 0)
            {
                box_int -= 10000;
                textBox.Text = box_int.ToString();
                textBox.SelectionStart= 0; 
                return; 
            }
       } 

如何防止上下键在c# windows窗体中移动文本框中的插入符号/光标到左右?

为了防止插入符号(而不是光标)移动,您应该在事件处理程序中设置e.Handled = true;。此代码将在按下向上或向下箭头时更改插入符号右侧的数字。如果按下向上或向下箭头,则将e.Handled设置为true,以防止插入符号移动。这段代码没有经过完全测试,但似乎可以工作。我还将文本框ReadOnly属性设置为true,并预设值为"0"。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    //Only change the digit if there is no selection
    if (textBox.SelectionLength == 0)
    {
        //Save the current caret position to restore it later
        int selStart = textBox.SelectionStart;
        //These next few lines determines how much to add or subtract
        //from the value based on the caret position in the number.
        int box_int = 0;
        Int32.TryParse(textBox.Text, out box_int);
        int powerOf10 = textBox.Text.Length - textBox.SelectionStart - 1;
        //If the number is negative, the SelectionStart will be off by one
        if (box_int < 0)
        {
            powerOf10++;
        }
        //Calculate the amount to change the textbox value by.
        int valueChange = (int)Math.Pow(10.0, (double)powerOf10);
        if (e.KeyCode == Keys.Down)
        {
            box_int -= valueChange;
            e.Handled = true;
        }
        if (e.KeyCode == Keys.Up)
        {
            box_int += valueChange;
            e.Handled = true;
        }
        textBox.Text = box_int.ToString();
        textBox.SelectionStart = selStart;
    }
}