Thank you for your support!    
UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Edit Discussion
> Tracking A Textbox Cursor    

Tracking A Textbox Cursor

This article provides a brief description of how to track a textbox's cursor position and selection data.

Contents

Reasons for Tracking

We might like to know the current position of the cursor and it's selection state within a textbox to provide a means to add or replace some standardized text into the string at the given location. For instance, in a case where we'd like to have the user be able to click a button to add a keyword of some sort into the text at the current position of the cursor.


Problems in Tracking

In the scenario described above, when the user clicks a button, or otherwise causes the loss of focus on the textbox, the SelStart and SelLength properties are no longer programmatically available to us. Therefore, we require a method to store this information for use when the user has the focus set somewhere other than the textbox in question.


How to Track the Cursor

Tracking the cursor data is a simple matter of using two events of the textbox (the KeyUp and MouseUp events) and providing two form scope variables to hold the information that other code in the form will be able to access. Here is an example of how it works:

CODE

Option Compare Database
Option Explicit

'start position of the cursor within ctlText
Private CursorPosition As Integer

'selection length of the cursor within ctlText
Private CursorLen As Integer


'track the cursor state when a key is released
Private Sub ctlText_KeyUp(KeyCode As Integer, Shift As Integer)
 CursorPosition = Me.ctlText.selStart
 CursorLen = Me.ctlText.SelLength
End Sub

'track the cursor state when the mouse button is released
Private Sub ctlText_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
 CursorPosition = Me.ctlText.selStart
 CursorLen = Me.ctlText.SelLength
End Sub


We now have the CursorPosition and CursorLength variables which are always updated to the latest cursor state and can be accessed from any other code in the form's module. These are Integer values that we can use to manipulate the text in the ctlText control using the built in text evaluation and manipulation functions such as Instr() and Replace().


See Also

Function: ReplaceViaPosition.
This function can be used in conjunction with a cursor Start and Length values to add some text to the original string.

Edit Discussion
This page was last modified 02:05, 9 February 2012.  This page has been accessed 363 times.  Disclaimers