简体   繁体   中英

C#, winform - List box selection using up and down arrow key?

I have list box, I am able to select the entries (Single select mode - one at a time) using keyboard and mouse, but when i use up and down arrow keys, its not selecting the list. But able to scroll the list with an underline below each entity the arrow key is related. Thanks

Add a handler to Form1.KeyDown event:

private Form1_KeyDown(object sender, KeyEventArgs e)
{
  this.listBox1.Focus();
  this.listBox1.Select();

  if (e.Key == Keys.Up)
  {
    this.listBox1.SelectedIndex--;  
  }
  else if (e.Key == Keys.Down)
  {
    this.listBox1.SelectedIndex++;
  }
}

I think you can do this using the SendMessage API. Something like this:

private const int WM_VSCROLL = 0x115;

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);

private void listBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        SendMessage(this.listBox.Handle, (uint)WM_VSCROLL, (System.UIntPtr)ScrollEventType.SmallIncrement, (System.IntPtr)0);
        e.Handled = true;
    }

    if (e.KeyCode == Keys.Up)
    {
        SendMessage(this.listBox.Handle, (uint)WM_VSCROLL, (System.UIntPtr)ScrollEventType.SmallDecrement, (System.IntPtr)0);
        e.Handled = true;
    }
}

I have write this code

     private void listBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)
        {
            int indicee = listBox1.SelectedIndex;
            label2.Text = indicee.ToString();
        }
        if (e.KeyCode == Keys.Down)
        {
            int indicee = listBox1.SelectedIndex;
            label2.Text = indicee.ToString();
        }

but when press down the index dont change , i think the code must be in other event.

This is the best way , its working fine for me

         private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {   
        int indicee = listBox1.SelectedIndex +1;
        label6.Text = indicee.ToString();
        ni = indicee-1;
        if (ni >= 0)
        { loadender(ni); }

When you moves with arrows keys the index of the listbox changes too, then you write your code in this event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM