[英]C#, winform - List box selection using up and down arrow key?
我有列表框,我能够使用键盘和鼠标选择条目(单选模式-一次选择一个),但是当我使用向上和向下箭头键时,它不会选择列表。 但是,能够滚动列表的每个实体下方带有下划线的箭头键是相关的。 谢谢
将处理程序添加到Form1.KeyDown事件:
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++;
}
}
我认为您可以使用SendMessage API做到这一点。 像这样的东西:
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;
}
}
我已经写了这段代码
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();
}
但是当按下索引时不要更改,我认为代码必须在其他情况下。
这是最好的方法,对我来说很好
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); }
当您使用箭头键移动时,列表框的索引也会更改,然后在此事件中编写代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.