日期:2014-05-18  浏览次数:20734 次

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");
        }