如何在C# Windows窗体中防止上下箭头将光标移动到文本框的左右?

4
我正在尝试将光标的索引增加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; 
            }
       } 
1个回答

8
为了防止插入符(不是光标)移动,您应该在事件处理程序中设置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;
    }
}

删除了我意外的双重发布。 - Chris Dunaway
1
啊,我完全忘记了 e.Handed。谢谢你优雅的解决方案,也让值增加了!非常有帮助!谢谢!!! - aramnaz
e.Handled 对我的略有不同的问题也非常完美,谢谢! - RaviRavioli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接