Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can listbox keydown be disabled?

Status
Not open for further replies.

SkennyR

Programmer
Mar 7, 2004
157
US
Hi..
I have a form with one list box on it. (named List1)
I enter the following code in sub Form_load:

for x= 1 to 10
list1.additem x
next
list1.additem "Hello"
list1.additem "World"
list1.additem "How are you"
list1.additem "today?"
end sub

Now, when I run it, I can scroll through the items in the list box using up and down keys, but if I press key "1" on keyboard, it always goes back to the first item, which is a "1".
I need the listbox's cursor (list1.selected) to stay where it is, if I press key "1".
In other words, I want the listbox to ignore the keyboard "1" key.
I have form keypreview set to true.
Is there anyway to do this? If so, how?
Thanks!

 
Set the form's KeyPreview property to TRUE.
Define a KeyPress event for the list box to capture key presses, and then remove the keypress (by setting KeyAscii = 0)

Code:
Option Explicit

Private Sub Form_Load()
    
    Dim x As Long
    
    Me.KeyPreview = True
    
    For x = 1 To 10
        List1.AddItem x
    Next
    
    List1.AddItem "Hello"
    List1.AddItem "World"
    List1.AddItem "How are you"
    List1.AddItem "today?"
    
End Sub

Private Sub List1_KeyPress(KeyAscii As Integer)

    KeyAscii = 0
    
End Sub

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Private Sub List1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode > 47 And KeyCode < 58 Then KeyCode = 0
End Sub

if you want other letters to work...
 
Gmmastros:
I already had the form.keypreview set to true.
But i didnt have your other suggestion:

Private Sub List1_KeyPress(KeyAscii As Integer)
KeyAscii = 0
End Sub

I added that and it works great!!
Thanks.
MattStech:
I tried your suggestion, but it didnt work for me.
Thanks though, I really appreciate it.
You guys are the greatest!
 
Glad to help.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
I am a small amount of an idiot today it needs to be in the keypress event. Didn't have time to test before I sent it off
Matt
Private Sub List1_KeyPress(KeyAscii As Integer)
If KeyAscii > 47 And KeyAscii < 58 Then KeyAscii = 0
End Sub
 
MattSTech, no prob.. I know exactly how it feels to be an idiot, however I dont do it in a small way. LOL
Thanks again, and have a good day!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top