个人未完成的网站

WPF和WindowsForm下的按下Enter跳转下一个控件通用方法

WP下按下回车(enter)跳转下一个控件 上代码:

protected override void OnKeyDown(KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                // MoveFocus takes a TraveralReqest as its argument.
                TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);

                // Gets the element with keyboard focus.
                UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

                // Change keyboard focus.
                if (elementWithFocus != null)
                {
                    elementWithFocus.MoveFocus(request);
                }
                e.Handled = true;
            }
            base.OnKeyDown(e);
        }

在窗体里写上就可以了。

 

WindowsForm下的按下回车(Enter)跳转到下一个控件

 /// <summary>
        /// 方法一:实现按下回车跳到下一个控件(不论是什么控件,如果需要可以在里面加上对控件类型的判断)
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyDown(KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                int i = 0;
                foreach (Control c in this.Controls)
                {
                    if (c.Focused)
                    {
                        i = c.TabIndex;
                        break;
                    }
                }
                foreach (Control c in this.Controls)
                {
                    if (c.TabIndex == (i + 1))
                    {
                        c.Focus();
                        break;
                    }
                }

            }
        }
        /// <summary>
        /// 方法二:灵活方便,可以通过方法中的参数控制是否要进入控件的子控件中,是否忽略tobstop的设置。
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            //base.OnKeyPress(e);
            if (e.KeyChar == (char)13)
            {
                e.Handled = true;
                this.SelectNextControl(this.ActiveControl, true, true, true, false);
            }
        }
        /// <summary>
        /// 方法三:直接将enter按键转化为tab按键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show("");
            if (e.KeyCode == Keys.Enter)
            {
                SendKeys.Send("{TAB}");
                e.Handled = true;
            }
        }

具体写在哪个事件里面,以个人情况决定。

posted on 2012-07-02 18:41  我是小虫  阅读(2139)  评论(0编辑  收藏  举报

导航