开发者

Is there a way to have a universal KeyDown Handler and Focus move with TabIndex in C#.NET?

I want to run a common KeyDown even handler for all the controls available on a form. any way I can accom开发者_运维技巧plish that?

To be more clear, my intention is to detect Enter key whenever it's pressed and move the focus from the current control to the one with next TabIndex.

How can I accomplish that?


You'll have to avoid getting in the way of regular use of the Enter key. This should be close:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == Keys.Enter && this.AcceptButton == null && this.ActiveControl != null) {
    TextBoxBase box = this.ActiveControl as TextBoxBase;
    if (box == null || !box.Multiline) {
      // Not a dialog, not a multi-line textbox; we can use Enter for tabbing
      this.SelectNextControl(this.ActiveControl, true, true, true, true);
      return true;
    }
  }
  return base.ProcessCmdKey(ref msg, keyData);
}


Override the form's ProcessCmdKey method.


actually ProcessCmdKey doesn't occur under the form events list, so couldn't use it earlier. ^_^

I Edited a bit and modified it to detect if any buttons are available and if there is, it'll not move focus, instead press the button..

Button b = this.ActiveControl as Button;
        if (keyData == Keys.Enter && this.AcceptButton == null && this.ActiveControl != null && !this.ActiveControl.Equals(b))
        {

            TextBoxBase box = this.ActiveControl as TextBoxBase;

            if (box == null || !box.Multiline)
            {
                // Not a dialog, not a multi-line textbox; we can use Enter for tabbing
                this.SelectNextControl(this.ActiveControl, true, true, true, true);
                return true;
            }
        }
        return base.ProcessCmdKey(ref msg, keyData);

But whatif I want to press the button once and then move again to the new control? Is there any way to invoke this ProcessCmdKey manually?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜