给所有的Control添加发送键盘事件Tab事件,实现回车键自动跳转到下一个控件[基于Shark Xu]

Shark Xu 的文章给所有的Control加两个属性,实现回车键自动跳转到下一个控件 中给我们提供了一个方法实现的Windows应用程序中按回车键或者上下键,在输入项之间自动跳转。确实解决很大的问题,减少了代码量。honyoung 提出利用发送Tab事件来解决这个问题。  即简化了设置两个属性的步骤(特别是在设置下一个或上一个时选择控件时很容易出错)。同时在VS.NET中又提供了TabIndex属性,这样很容易造成ControlFocus的属性和TabIndex不相匹配的地方。于是我在Shark Xu的基础上实现了“给所有的Control添加发送键盘事件Tab事件,实现回车键自动跳转到下一个控件 ”下面是具体的实现代码:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Collections;


namespace sxu
{
    [ProvideProperty(
"AllowKeyTab"typeof(Component))]
    
public partial class KeyTab : Component, IExtenderProvider
    
{
        
public Keys NextK;
        
public Keys PreviousK;
        Hashtable _hashTable 
= new Hashtable();
       

        
Constructor

        
属性AllowKeyTab

        
        
/// <summary>
        
/// 用于属性检索
          
/// </summary>
        
/// <param name="component"></param>
        
/// <returns></returns>

        public bool GetKeyTab(Component component)
        
{
            
if (_hashTable.Contains(component))
            
{
                
return (bool)_hashTable[component];
            }


            
return false;
        }

        
private void currentC_KeyDown(object sender, KeyEventArgs e)
        
{

            
if (e.KeyCode == this.NextK)
            
{
                SendKeys.Send(
"{TAB}");
            }

            
else if (e.KeyCode == this.PreviousK)
            
{
                SendKeys.Send(
"+{TAB}");//发送shift+tab
            }

        }


        
public bool CanExtend(object component)
        
{
            
//必须是普通控件(排出Form)才支持扩展 
            if (component is Control && !(component is Form))
            
{
                
return true;
            }


            
return false;
        }



       
       
    }

}

在Form中的加入如下代码:
private void Form1_Load(object sender, EventArgs e)
        
{
            
this.keyTab1.NextK = Keys.Down;
            
this.keyTab1.PreviousK = Keys.Up;
        }
o_ddd.JPG
程序代码请下载
posted @ 2006-08-25 21:50  绥山潇洒哥  阅读(3927)  评论(10编辑  收藏  举报