0

I have a UserControl which contains a button and a textbox. User should eighter fill the textbox and click the button - so that the data is sent to the form and the usercontrol is hidden, or press Escape on the textbox - so that the form knows user has canceled the progress.

The issue is that when the user presses tab on the textbox, the usercontrol is leaved (and hidden afterward - due to the strategy of hiding usercontrol when leaved) so neighter a data is sent to the form, nor user has canceled the progress.

All the usercontrol, the textbox and the button inside are having their TabStop set to false but user can still come back to the form with pressing tab.

How can I prevent the tab functionality on this usercontrol? I want to make the rule: click the button or press Escape, no tab runaway, that's it.

Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94
  • That's very poor UI design. You shouldn't prevent the user from using the keyboard in a familiar way. You should rethink how you're handling input. – xxbbcc Jul 22 '14 at 22:41
  • I've just posted a link in my answer that has an example in which it shows how to do nearly exactly what you need. – pid Jul 22 '14 at 22:41
  • @xxbbcc: I agree, those things are better left as expected and even leveraged. An impaired person might have huge troubles using software that is too far off the UI guidelines. Still, he wants an answer. Who knows why he needs this? – pid Jul 22 '14 at 22:42
  • @xxbbcc I know it is not an acceptable way, but unfortunately my customer is a company who builds applications for people who are actually old and traditional people, so they want their own way of doing things :) – Mahdi Tahsildari Jul 22 '14 at 22:47

2 Answers2

0

Set TabStop to false on all other controls in the form so that on tabbing the focus stays there. Otherwise, swallow the keypress in the OnKeyDown or OnKeyPress event. Single the tab key out and prevent it from being processed any further: capture key presses.

pid
  • 11,472
  • 6
  • 34
  • 63
  • thanks for the answer but I have tested this before, the problem with this approach is that you lose tab usage at all. Is there any other way to trap the tab key inside the user control? – Mahdi Tahsildari Jul 22 '14 at 22:49
  • Yes, look at the example in the link I've posted. Attach the event handler just to the textbox and filter it properly. It shouldn't interfere with anything else on the form. – pid Jul 22 '14 at 22:54
0

Use the Validating method in your UserControl:

public partial class UserControl1 : UserControl {

  public UserControl1() {
    InitializeComponent();
  }

  protected override void OnValidating(CancelEventArgs e) {
    e.Cancel = (textBox1.Text.Trim() == String.Empty);
    base.OnValidating(e);
  }
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225