Capture keypress without triggering Key_Press event of a text box

randika100100

Registered User.
Local time
Tomorrow, 05:31
Joined
Aug 31, 2011
Messages
11
Hi all!
Im pretty new to the forum and to VBA. This is my first post. I have a problem that I have been trying to solve for 2 days and yet couldn't .

I want to detect if the space bar has pressed. But I want to do this in the Key_Change event. In other words I want to know how to detect the key without triggering Key_Press event. Can someone please help me?

Thanks in advance.
 
I want to know how to detect the key without triggering Key_Press event. .
I think you need to understand that the event will occur if a key is pressed, regardless of whether you want it to happen or not. What you do with it is another matter. You can ignore it (not put any code in it) or you can redirect it, like setting the KeyCode to 0. So for example:

Code:
Private Sub Text0_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 32 Then KeyCode = 0
End Sub
 
@ boblarson

Thank you very much for the reply. It was my fault that I haven't described my matter properly. I have a subform in datasheet view and a text box to put values to search and the results are displayed in the datasheet.I have code in Text_Change Event so whenever user press a button inside the text box, it will setup the sql and requery the datasheet to provide a live search. But in the process of setting up the query, it will lose focus from the text box and as a solution I put

Me.filterValue.SetFocus
Me.filterValue.SelStart = Me.filterValue.SelLength

to set the cursor back on the correct position inside the textbox so user can keep typing. I want to be able to detect if user has pressed space then I have to set it like

Me.filterValue.SetFocus
Me.filterValue.SelStart = Me.filterValue.SelLength + 1

So I tried this

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

If KeyCode=32 Then

Me.filterValue.SetFocus
Me.filterValue.SelStart = Me.filterValue.SelLength + 1

Else

Me.filterValue.SetFocus
Me.filterValue.SelStart = Me.filterValue.SelLength

End Sub

But unfortunately it doesn't work. I can't understand why. The SelLength only seems to work outside the KeyDown_Event. It works perfectly when I put it in the Text_Change event and it sets the cursor in the correct position. But then I can’t see a way to get the keycode when im in Text_Change Event to allow user to put space between text. Thanks in advance and your help is very much appreciated
 

Users who are viewing this thread

Back
Top Bottom