Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms: Textbox Leave event doesn't get fired after going to main menu

Tags:

c#

.net

winforms

I have a TextBox control on my Form. I use the Leave event on the control to process user input. It works fine if the user clicks on some other control on the form, but the even doesn't get fired when the user goes straight to the main menu. Any ideas which event should I use to get it fired everytime?

like image 396
Grzenio Avatar asked Dec 01 '08 14:12

Grzenio


3 Answers

I found a reasonable workaround, I set the focus on the main menu manually:

EDIT: As suggested by @TcKs, I changed the event from ItemClicked to MenuActivate. Thanks very much for help!

    private void menuStrip1_MenuActivate( object sender, EventArgs e )
    {
        menuStrip1.Focus();
    }
like image 192
Grzenio Avatar answered Sep 28 '22 05:09

Grzenio


You should use "Validating" and "Validated" events for checking user's input. Then if user go to another control "A", and the control "A" has property "CausesValidation" set to "true" ( its default value ) the "Validating" and "Validated" event will be fired.

The menu has "CausesValidation" property too.

Edit: Sorry, I forgot the "CausesValidation" in menu strip is our functionality and not built-in. But the check for validating is pretty simple:

private void menuStrip1_MenuActivate( object sender, EventArgs e ) {
    bool ret = this.Validate( false );
    if ( false == ret ) {
        // user's input is wrong
    }
}

Use any ContainerControl instead of "this", if you want check the validation in another control than the "this" form. For example in MDI Child window.

like image 25
TcKs Avatar answered Sep 28 '22 07:09

TcKs


There are some cases when Lostfocus is not fired, for example clicking toolbar buttons and menu items. I use to work around this with a local "LastControl" variable and handle it myself when the menu got focus.

There are reasons that menu click does not loses the textbox focus. If you want to have for example an "Edit" menu with "Paste" in, the "Paste" should act against the control that has focus and because of that it must not steal the focus from any controls on the form.

So the menu can be seen as a context menu that not steal the focus from the control.

like image 29
Stefan Avatar answered Sep 28 '22 07:09

Stefan