Search code examples
c#winformskeyboard-shortcutslinklabel

Using keyboard shortcuts with LinkLabel controls


I've noticed that keyboard-shortcuts assigned to linklabel controls in standard .NET WinForms forms are not functioning.

I have created a LinkLabel control instance and assigned the Text property to be "Select &All". For most controls (label, button, radio button, etc) this would cause Alt+A to become the designated keyboard shortcut to trigger the default event (Clicked). This is not happening for the LinkLabel (though it is working okay for other controls)

  • I have verified that the keyboard shortcut is not a duplicate.
  • I have checked to see if the shortcut is setting the focus rather than triggering Clicked. The focus remains unchanged.
  • I have verified that the UseMnemonic property is set to true.

Any ideas?


Solution

Thank you Charlie for the correct answer. Exactly what I needed. I made a slight modification since this code snippet wouldn't compile as-is. LinkLabelLinkClickedEventArgs requires a LinkLabel.Link as a construction parameter rather thank a LinkLabel.

class LinkLabelEx : LinkLabel
{
    protected override bool ProcessMnemonic(char charCode)
    {
        if (base.ProcessMnemonic(charCode))
        {
            if (this.Links.Count == 0)
                return false;
            OnLinkClicked(new LinkLabelLinkClickedEventArgs(this.Links[0]));
            return true;
        }
        return false;
    }
}

Solution

  • I believe this is just a shortcoming of LinkLabel; it doesn't generate a click event when you use its mnemonic. However, I've used the following code as a workaround with good success:

    class BetterLinkLabel : LinkLabel
    {
      protected override bool ProcessMnemonic( char charCode )
      {
        if( base.ProcessMnemonic( charCode ) )
        {
          // TODO: pass a valid LinkLabel.Link to the event arg ctor
          OnLinkClicked( new LinkLabelLinkClickedEventArgs( null ) );
          return true;
        }
        return false;
      }
    }