0

I made a form and created a command button control. I would like to make it so that when the user presses the command button it sends a keystroke to a listbox of my choice.

Specifically, I want the command button to send a "down" arrow keystroke to a listbox (which will have focus) so that it goes from the current item to the next item.

How do I do this?

Let's say the name of my listbox is "lstFruits". I gave it focus, then tried SendKey.

Form.lstFruits.SetFocus.
SendKeys.Send ("{DOWN}")

Got the error "Argument not optional".

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
MrPatterns
  • 4,184
  • 27
  • 65
  • 85
  • See [Alex K.'s answer](http://stackoverflow.com/a/9361643/11683) for the answer; as for the error, see http://stackoverflow.com/questions/8070033/c-sharp-dll-cannot-affect-value-of-a-number-passed-by-reference-from-a-vb6-appli/8070104#8070104. – GSerg Feb 20 '12 at 13:15

1 Answers1

2

There is no need to emulate a keystroke, you can control the listbox in code;

lstFruits.SetFocus
if ((lstFruits.listindex + 1) < lstFruits.listcount) then
    lstFruits.listindex = lstFruits.listindex+ 1
endif

Edit

Dim strName As String
strName = "lstFruits"

Dim lst As VB.ListBox: Set lst = TheForm.Controls(strName)

lst.SetFocus
If ((lst.ListIndex + 1) < lst.ListCount) Then
    lst.ListIndex = lst.ListIndex + 1
End If
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • hi Alex K. thanks for your response! what if I have a string that contains the name of the listbox? Say strName = lstFruits. how do I use your code so that it can take the string and then move down the listbox? – MrPatterns Feb 20 '12 at 13:22
  • Updated above, although usually you would never need to store the name as a string. – Alex K. Feb 20 '12 at 13:34