I have list box, I a开发者_开发知识库m 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.
精彩评论