Preventing BackSpace key in a TextBox from moving a cursor to the previous control

topic: 

Deleting characters in a TextBox with Backspace key doesn't stop when cursor reaches the beginning position but unexpectedly moves cursor to the previous control. It could cause unintended deletion of the data there.


To stop BackSpace key from leaving a TextBox and behave the same way as in other applications, add following code to a TextBox Keypress event. If you're using a Framework, add it to your lowest level TextBox class so it will be inherited by all TextBoxes.

This is sample code. Add error handling and adjust to your requirements as necessary.

1
2
3
4
5
6
7
8

* TextBox Keypress
LPARAMETERS nKeyCode, nShiftAltCtrl
IF nKeyCode = 127 AND This.SelStart = 0 AND This.SelLength = 0
	NODEFAULT
ENDIF

Comments

i've included similar code in the LostFocus event of my controls.
it seems more apropiate there than in the KeyPress event

I have similar code on LostFocus but it is much better put it to KeyPress event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
*** Form's INIT EVENT CODE
FOR i = 1 TO thisform.Objects.Count
	IF thisform.Objects(i).baseclass = "Textbox"
		BINDEVENT(thisform.Objects(i), "KeyPress", thisform, "KeyPress_BackSpace")
	ENDIF
ENDFOR

*** Form's KeyPress_BackSpace EVENT CODE
LPARAMETERS nKeyCode, nShiftAltCtrl
C_SelStart  =thisform.ActiveControl.SelStart
C_SelLength  =thisform.ActiveControl.SelLength
IF nKeyCode = 127 AND C_SelStart = 0 AND C_SelLength = 0
	NODEFAULT
ENDIF   

If I have a PageFrame and this pagreframe have textboxes, How I can do to make this code also affects those textboxes?

,
You really did good. working very very fine.
Just change the "KeyPress_backSpace" with "KeyPress" only, and its really working.
thanks a lot.

Mr. Afaq Zahoor