Disabling A Button Control Mnemonic

File this as another issue that should have been really easy to resolve, but ended up taking longer than it should have.   

We had a problem where users were “not able to type an ‘S’”.  What?  That’s pretty strange. 


Turned out that they could type an ‘S’, but every time they did, the current page would attempt to save their work.  What was happening?  The ‘S’ key was assigned as a mnemonic for the Save button.  Pages in the application contained user controls.  And, most of the user controls had Save buttons.  All of the buttons had mnemonics assigned.  The expected behavior was that the Alt key would need to pressed in order to activate the mnemonic, but of course, that’s not the case.  A button’s mnemonics are always active when its form has focus.


Once that became obvious, it was assumed there would be a straightforward solution.  In the end, there is.  But, it wasn’t so easy to discover (apparantly not many people have wanted to squash the default behavior).


There were a few discoveries along the way.  One is that there is an overridable method for the Control class, ProcessMnemonic.  This method allows you to add custom handling when the control’s mnemonic is pressed (exactly what we needed).  Returning true indicates that the given character code is the mnemonic and was processed.  Returning false indicates that the given character code either was not the mnemonic or was not processed.


Accompanying ProcessMnemonic is IsMnemonic.  This method determines if the given character code is the mnemonic for a given string.  We could pass in the character code given to the ProcessMnemonic method along with the button’s text.  If the character in question is not our mnemonic, we can just return false to ignore it.


The next portion of the problem was to determine if the Alt key is in a pressed state.  The Control class provides a static property to do just that, Control.ModifierKeys.


The final step is to perform the mnemonic action when needed.  I’ve just used the base.ProcessMnemonic method, but alternatively, I could have called PerformClick and returned true.


The result, below, allows us to only process the mnemonic if the Alt key pressed, and once again allows users type an ‘S’ whenever they need (and hopefully, it saves you the time that we lost).


protected override bool ProcessMnemonic(char charCode)


if (CanSelect && IsMnemonic(charCode, Text) && (Control.ModifierKeys == Keys.Alt))

             return base.ProcessMnemonic(charCode);


return false;





Rss Feed