How to find the name of the control the caret is in.

  • Thread starter Thread starter ThomasAJ
  • Start date Start date
T

ThomasAJ

I have some code that will insert a string into where the caret is positioned
in a text box. So if a shortcut is entered like say Alt+1 a string is
inserted. This works fine when I hard code the text box name.

However I want to make it generic so the code can be used across the project
for all text controls.

So I need to know the name of the Text box that a caret is in so I can pass
it to the generic procedure. I also need to make sure the focus is on the
same control as the caret is in.
 
Yes I've tried Me.ActiveControl (in my test form as per code below) but when
the Alt key is pressed the code does not know about it. eg it's name.

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Dim ctrl As Control

Dim blnAlt As Boolean
Dim strPrior As String 'Text before the cursor.
Dim strAfter As String 'Text after the cursor.
Dim lngLen As Long 'Number of characters
Dim iSelStart As Integer 'Where cursor is.

Set ctrl = Me.ActiveControl

etc


End Sub
--
Regards
Tom


Allen Browne said:
Try:
Screen.ActiveControl
 
That should work if you turned on the form's KeyPreview property.

(Note that the Alt key itself triggers the event also.)

--
Allen Browne - Microsoft MVP. Perth, Western Australia

Reply to group, rather than allenbrowne at mvps dot org.


ThomasAJ said:
Yes I've tried Me.ActiveControl (in my test form as per code below) but
when
the Alt key is pressed the code does not know about it. eg it's name.

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Dim ctrl As Control

Dim blnAlt As Boolean
Dim strPrior As String 'Text before the cursor.
Dim strAfter As String 'Text after the cursor.
Dim lngLen As Long 'Number of characters
Dim iSelStart As Integer 'Where cursor is.

Set ctrl = Me.ActiveControl

etc


End Sub
 
Back
Top