Saturday 28 June 2008

How to build a custom control that responds to focus events

This snippet should let you build a panel that can receive and pass focus on when either the up or down key is pressed. This is ideal for use on a Smartphone for when you need a list of custom controls. The trick is to use the CF2 function SelectNextControl. Another trick I added is to search up the parent tree so that focus can still be passed from a control which is inside another panel to one which is not, for example one which is just on the form. Remember if you are going to paint a focus rect you need to add Invalidate into the OnGotFocus and OnLostFocus overridden events. Then in your OnPaint you can check if Focused and paint accordingly.
protected override void OnKeyDown(KeyEventArgs e)
{
Control c = this;
switch (e.KeyCode)
{
case Keys.Up:
while ((c = c.Parent) != null && !c.SelectNextControl(this, false, true, true, true));
break;
case Keys.Down:
while ((c = c.Parent) != null && !c.SelectNextControl(this, true, true, true, true)) ;
break;
}
base.OnKeyDown(e);
}

No comments: