读书人

winform反射控件时添加怎么获取获取焦

发布时间: 2012-08-15 16:57:16 作者: rapoo

winform反射控件时添加如何获取获取焦点事件
public static void InitFont(System.Windows.Forms.ContainerControl form)
{
Type fieldType = form.GetType();
FieldInfo[] fieldsInfor = fieldType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo fi in fieldsInfor)
{
if (fi.FieldType.Name == "TextBox")
{





}
}
}
我获取到如果是文本框就添加一个获取焦点事件
怎么添加这个事件啊

[解决办法]
继续对textbox反射它的事件,然后对事件进行绑定AddEventHandler
[解决办法]

C# code
public void SetEvent(Control parContainer)        {            for (int index = 0; index < parContainer.Controls.Count; index++)            {                // 如果是容器类控件,递归调用自己                if (parContainer.Controls[index].HasChildren)                {                    SetEvent(parContainer.Controls[index]);                }                else                {                    if(parContainer.Controls[index].GetType().Name == "TextBox")                    {                        parContainer.Controls[index].GotFocus += 事件名;                    }                }            }        }public static void InitFont(System.Windows.Forms.ContainerControl form)  {    SetEvent(form);  }
[解决办法]
C# code
private void Form1_Load(object sender, EventArgs e)        {                       // this.textBox2是窗体上的一个TextBox控件,动态添加焦点事件            EventInfo evt = this.textBox2.GetType().GetEvent("Enter",                    BindingFlags.NonPublic | BindingFlags.Instance                    | BindingFlags.Public                );            evt.AddEventHandler(this.textBox2, new EventHandler(textBox1_Enter));                }        //焦点处理事件        private void textBox1_Enter(object sender, EventArgs e)        {            MessageBox.Show("OK");        } 

读书人网 >C#

热点推荐