【发布时间】:2011-10-06 10:01:01
【问题描述】:
我有列表框,我可以使用键盘和鼠标选择条目(单选模式 - 一次一个),但是当我使用向上和向下箭头键时,它不会选择列表。但是能够在每个实体下方使用下划线滚动列表,箭头键是相关的。谢谢
【问题讨论】:
-
所以基本上当你按下上/下时你想滚动列表而不是选择下一个/上一个项目?
我有列表框,我可以使用键盘和鼠标选择条目(单选模式 - 一次一个),但是当我使用向上和向下箭头键时,它不会选择列表。但是能够在每个实体下方使用下划线滚动列表,箭头键是相关的。谢谢
【问题讨论】:
为 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); }
当您使用箭头键移动时,列表框的索引也会发生变化,然后您在此事件中编写代码。
【讨论】: