Sunday, August 20, 2006

Getting ActiveControl in Compact Framework

 The Compact Framework does not have a property for ActiveControl. This is a bit of a PITA really. The following is some code that you can use to add an Active Control to your forms:

public virtual Control ActiveControl
{
   get
   {
      return GetFocusedControl(this);
   }
   set
   {
      if (!value.Focused)
      {
         value.Focus();
      }
   }

}

private Control GetFocusedControl(Control parent)
{
   if (parent.Focused)
   {
      return parent;
   }
   foreach (Control ctrl in parent.Controls)
   {
      Control temp = GetFocusedControl(ctrl);
      if (temp != null)
      {
         return temp;
      }
   }
   return null;

}
I normally just add this in the form.designer.cs file to get it out of the main code, or you could create a new class called ActiveControlForm or something and bang it in there and inherit all your forms from this rather than System.Windows.Form.

2 comments:

Anonymous said...

Works fine, thanks!!

Tiago Becker said...

Nice, helped a lot! thanks!!!