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 trying increase index of cursor 1. example, if blinking cursor between 2 , 1 in 210, increase value 220.

this part of code i'm using right now. i'm trying cursor stay in place after pressing down, , moving right. tried set selectionstart 0 box increases 1 default (my textbox's first caret index starts on 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;              }        }  

in order prevent caret (not cursor) moving, should set e.handled = true; in event handler. code changes digit right of caret when or down arrow pressed. if or down arrow pressed, e.handled set true prevent movement of caret. code not tested, seems work. set textbox readonly property true , preset value "0".

private void textbox1_keydown(object sender, keyeventargs e) {      textbox textbox = (textbox)sender;      //only change digit if there no selection     if (textbox.selectionlength == 0)     {         //save current caret position restore later         int selstart = textbox.selectionstart;          //these next few lines determines how add or subtract         //from value based on caret position in number.         int box_int = 0;         int32.tryparse(textbox.text, out box_int);          int powerof10 = textbox.text.length - textbox.selectionstart - 1;         //if number negative, selectionstart off 1         if (box_int < 0)         {             powerof10++;         }          //calculate amount change 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;     } } 

Comments