2011-10-06 117 views
1

我有列表框,我可以使用鍵盤和鼠標選擇條目(單選模式 - 一次一個),但是當我使用向上和向下箭頭鍵時,它不會選擇列表。但能夠使用箭頭鍵相關的每個實體下方的下劃線滾動列表。由於C#,winform - 使用向上和向下箭頭鍵選擇列表框?

+0

所以基本上當你按下上/下你想要滾動列表而不是選擇下一個/上一個項目? –

+0

是的..這就是我需要的。 – Dhana

回答

2

添加處理程序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++; 
    } 
} 
1

我想你可以使用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; 
    } 
} 
0

我寫這篇文章的代碼

 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(); 
     } 

但是當按下了指數不改變,我認爲代碼必須在其他事件。

0

這是最好的方式,其對我來說

  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); } 

工作正常,當你移動的箭頭鍵列表框的指數變化太大,那麼你就寫你的代碼在此事件。

相關問題