C#中Windows通用的回车转Tab方法

2023-06-02,,

标签: windowsc#textboxbuttondropdownobject
2007-03-28 09:37 2773人阅读 评论(0) 收藏 举报

 分类:
C#(5) 

版权声明:本文为博主原创文章,未经博主允许不得转载。

方法1:
这个方法比较烦琐,就是为每个文本框的KeyPress增加:

if (e.KeyChar == '/r')
{
    SendKeys.Send("{TAB}");
}


方法2:
在方法1的基础上,还有一个比较聪明一些的做法,就是在窗体加载的时候为所有的文本框添加相同的按键事件处理,做法如下:
在Form_Load中添加AddEnterKeyDownEvent(this); 。 如:

        private void Form1_Load(object sender, EventArgs e)
        {
            //....
            AddEnterKeyDownEvent(this);
        }

函数AddEnterKeyDownEvent可以查找窗体中所有的TextBox和ComboBox类型控件并添加按键事件。代码如下:

        private void AddEnterKeyDownEvent(Control owner)
        {
            foreach (Control ctrl in owner.Controls)
            {
                if ((ctrl is TextBox) || (ctrl is ComboBox)) 
                {
                    //为TextBox或者ComboBox类型控件添加按键事件
                    ctrl.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EnterKeyDown);
                }
                else if((ctrl is GroupBox ) || (ctrl is Panel)) 
                {
                    //为GroupBox和Panel中的TextBox或者ComboBox类型控件添加
                    AddEnterKeyDownEvent(ctrl);
                }
            }
        }

对应的EnterKeyDown事件

private void EnterKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) 

    if(e.KeyCode==Keys.Enter) 
    { 
        SendKeys.Send("{TAB}"); 
    } 
}


方法3:
这个方法相对简单些:
把Form的KeyPreView设为true,然后在Form的KeyPress中增加下列代码即可:

if (e.KeyChar == ' /r')
{
    this.SelectNextControl(this.ActiveControl, true, true, true, true);
    //SendKeys.Send("{TAB}");//也可以使用这个代替SelectNextControl
}


这样会有个问题,按一次回车会电脑都会发出声音(DropDown样式的ComboBox),如果要去掉这个声音,就添加一句e.Handled = true;

if (e.KeyChar == '/r ')// 
{
    e.Handled = true;//通知系统,该KeyPress事件已经处理过

this.SelectNextControl(this.ActiveControl, true, true, true, true);
    //SendKeys.Send("{Tab}");  
}

嘿嘿,到这里好像偶尔会有问题,也许我们的KeyPress事件处理主要是将TextBox控件中的回车当成Tab处理,但碰到Button控件,比如“确定”按钮,那么Button的Click事件可能会失灵。我就碰到这样的情况,但在我给Button添加一个空的KeyPress事件处理函数后,这个问题又不存在了,然后我又将Button的KeyPress事件处理函数清除,Button的Click事件还正常工作,搞不懂是什么原因导致Button的Click事件失灵的,又是怎么活过来的!!

C#中Windows通用的回车转Tab方法的相关教程结束。

《C#中Windows通用的回车转Tab方法.doc》

下载本文的Word格式文档,以方便收藏与打印。