Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Can somebody tell me why hot keys of button skip textbox's leave event.

Recently, i encountered a strange problem as my current focus was on textbox and my button's hot key of save was Alt+S (hotkey created by writting &Save as text in button). Now whenever i press Alt+S the focus goes on button but textbox's leave event fails to fire. Can anybody give me an explanation why this is happening or is this suppose to happen?

Thanks in advance
Posted
Comments
[no name] 14-Feb-15 8:10am    
One form, several consumers of same "Event"...maybe time/order of subscription is important?

1 solution

I'm surprised that using a mnemonic key-combination on a Button would fire when a TextBox in WinForms has focus, because it "captures" the mouse, however I'm not surprised it doesn't fire the 'Leave Event in the sense that ties in with dim memories of being frustrated using mnemonics.

So, a few years ago I gave up on using mnemonics on WinForm Controls on a Form, or in Container Controls (for Menus they seem to work fine).

I use this kind of code now:
C#
// detect Alt-S
private Keys ShiftAltS = Keys.Shift | Keys.Alt | Keys.S;

// define in Form Scope
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData.HasFlag(ShiftAltS))
    {
        // test here to see if a particular Control
        // or Controls have the current Focus
        // and use a Switch/Case statement or whatever
        // to select which Control you want Focus to go to

        // here's a sample of what I would do to redirect Focus
        // from TextBox to Button:
        if(ActiveControl == YourTextBox)
        {
          YourButton.Focus();
          YourButton.Capture(); // optional: will have some side-effects
          return true;
        }
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
Actually, I use a fancier version of this that I intend to write an article or tip/trick about this year, here. But, this code, I hope, demonstrates a useful alternative if you don't get anywhere with mnemonics.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900