Pages

Thursday, November 12, 2009

Focus to next Control in winform on Enter Key Press C# By Praveen PR

Step 1.
//Add the funtion in any common class (static class) so the you can access if from any form you added

//Send Focus to next Control in Form
public static void sendTab(Keys sendKey, object sender)
{
if (sendKey == Keys.Enter)
{
SendKeys.Send("{TAB}");
}
else if (sendKey == Keys.Right)
{
//if (sender.GetType().Name != "DateTimePicker")
//{
// SendKeys.Send("{TAB}");
//}

if (sender.GetType().Name == "TextBox")
{
if (((TextBox)sender).SelectionStart == ((TextBox)sender).Text.Length)
{
SendKeys.Send("{TAB}");
}
}
if (sender.GetType().Name == "CustomTextBox")
{
if (((CustomControls.CustomTextBox)sender).SelectionStart == ((CustomControls.CustomTextBox)sender).Text.Length)
{
SendKeys.Send("{TAB}");
}
}
}

else if (sendKey == Keys.Left)
{
//if (sender.GetType().Name != "DateTimePicker")
//{
// SendKeys.Send("+{Tab}");
//}
if (sender.GetType().Name == "TextBox")
{
if (((TextBox)sender).SelectionStart == 0)
{
SendKeys.Send("+{Tab}");
}
}
  if (sender.GetType().Name == "CustomTextBox")// if any custom control created
{
if (((CustomControls.CustomTextBox)sender).SelectionStart == 0)
{
SendKeys.Send("+{Tab}");
}
}

}
}

Step2.

Add the following code in the form
#region Send Enter/ShiftTab Key


sprivate void sendControlKey(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Escape)
{
classGeneral.sendTab(e.KeyCode, sender);
}
else if (e.KeyCode == Keys.Escape)
{
classGeneral.closeFormOnEscapeKeyPress(this);
frmMainWindow.cFPurchaseGoodsRecptEst = null;
}
}
#endregion sendEnter/ShiftTabKey

 Step 3

Call the  sendControlKey funtion
e.g add a textbox and point the keydown event to  -->sendControlKey

Praveen PR

1 comment:

Anonymous said...

Very nice....Simple Its working