控件焦点_转移

转自 http://blog.csdn.net/candy1232009/article/details/7557729

在C#编程时,有时希望通过按回车键,控件焦点就会自动从一个控件跳转到下一个控件进行操作。 下面通过登录界面为例,讲解两种实现方法。

问题描述:

       以登录界面为例,当输入完用户名后, 若要输入密码,则密码对应的TextBox必须获得焦点, 一般的办法是用鼠标去点击就可以了。但是这样用户体验就会差一些(因为这样既要操作鼠标,又要操作键盘),其实可以实现按回车键就能自动获得下一个控件的焦点,这样直接用键盘输入就可以了,避免了鼠标的操作。

//解决办法一:  判断按键,手工跳转到指定法控件

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)   //  if (e.KeyValue == 13) 判断是回车键
            {
                this.textBox2.Focus();
            }
        }

//解决办法二: 根据控件TabIndex 属性顺序跳转

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Convert.ToChar(Keys.Enter))  
            {
                this.SelectNextControl(this.ActiveControl, true, true, true, true);  //需设置textBox的TabIndex顺序属性
            }
        }

//同样的方法,输入完成后,也可以按回车键直接登录

 private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                this.button1.Focus();
                button1_Click(sender, e);   //调用登录按钮的事件处理代码
            }
        }

Control.SelectNextControl 方法

/**
下面的代码示例演示具有用在某些控件的窗体中的 SelectNextControl 方法。 每次单击窗体都将激活下一个控件。 ActiveControl 属性在容器控件中获取当前激活的控件。
*/
private void Form1_Click(object sender, EventArgs e)
{
    Control ctl;
    ctl = (Control)sender;
    ctl.SelectNextControl(ActiveControl, true, true, true, true);
}

/**
下面的代码示例演示具有 Button 和用在其他某些控件的窗体中的 SelectNextControl 方法。 当单击 Button 时,将激活 Button 后的下一个控件。 请注意,您必须获取 Button 控件的父级。 由于 Button 不是容器,在 Button 上直接调用 SelectNextControl 不会更改激活。
*/
private void button1_Click(object sender, EventArgs e)
{
    Control p;
    p = ((Button) sender).Parent;
    p.SelectNextControl(ActiveControl, true, true, true, true);
}

最简单就是:

this.SelectNextControl(ActiveControl, true, true, true, true);

 

posted on 2013-05-03 11:21  laymond  阅读(1370)  评论(0编辑  收藏  举报

导航