开发者

Override default behavior of SPACE key in .net WinForms ListView

开发者 https://www.devze.com 2022-12-25 11:17 出处:网络
I\'d like to implement some custom behavior of Space key in a ListView. Basically I\'d like to toggle selected status of the item under cursor - that should be开发者_C百科 fairly simple

I'd like to implement some custom behavior of Space key in a ListView. Basically I'd like to toggle selected status of the item under cursor - that should be开发者_C百科 fairly simple

this.FocusedItem.Selected = !this.FocusedItem.Selected;

but alas, it also does the default action, which is to select the focused item. This way I am unable to 'unselect' the focused item. I've looked for similar problems and they suggest using PreviewKeyDown event, in which I would process the key and disallow the ListView to do its default action. But the PreviewKeyDown event argument has no "handled" property, so I cannot 'eat' this key.


This worked as you wanted:

private void listView1_KeyDown(object sender, KeyEventArgs e) {
  if (e.KeyData == Keys.Space) {
    listView1.FocusedItem.Selected = !listView1.FocusedItem.Selected;
    e.Handled = e.SuppressKeyPress = true;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消