aramnaz
aramnaz

Reputation: 53

How do I prevent the up and down keys from moving the caret/cursor in a textbox to the left and right in a c# windows form.

I'm currently trying to increase the index of the cursor by 1. For example, if my blinking cursor was between 2 and 1 in 210, it would increase the value to 220.

This is part of the code I'm using right now. I'm trying to get the cursor to stay in its place after pressing down, and its moving to the right. I tried to set the SelectionStart back to 0 but the box increases it by 1 by default (my textbox's first caret index starts on the very left).

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

Upvotes: 4

Views: 2431

Answers (1)

Chris Dunaway
Chris Dunaway

Reputation: 11216

In order to prevent the caret (not the cursor) from moving, you should set e.Handled = true; in your event handler. This code changes the digit to the right of the caret when the up or down arrow is pressed. If the up or down arrow is pressed, the e.Handled is set to true to prevent the movement of the caret. This code is not fully tested, but seems to work. I also set the textbox ReadOnly property to true and preset the value to "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;
    }
}

Upvotes: 8

Related Questions