Skip to main content
Logo Appt Light

Keyboard shortcuts on Xamarin

Most people operate their smartphones with touch, but some people use an external keyboard. Learning and using keyboard shortcuts can save you a lot of time. Shortcuts should always use a modifier key, such as CTRL or CMD to avoid clashing with system shortcuts.

Xamarin does not have support for hardware keyboard events. However, you can intercept key events inside the Android and iOS application.

The code example below shows a sample implementation for iOS.

public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
    if (keyCode == Keycode.KEYCODE_F && e.isCtrlPressed)
    {
        // Search
        return true
    }

    return base.OnKeyUp(keyCode, e);
}
[assembly: ExportRenderer(typeof(ContentPage), typeof(KeyboardPageRenderer))]
namespace KeyCommandsInXamarinForms.iOS
{
    public class KeyboardPageRenderer : PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || Element == null)
            {
                return;
            }

            // Create key command for Command + F
            UIKeyCommand command1 = UIKeyCommand.Create(
                new NSString("F"), 
                UIKeyModifierFlags.Command, 
                new ObjCRuntime.Selector("OnKeyPressed:")
            );

            this.AddKeyCommand(command1);
        }

        [Export("OnKeyPressed:")]
        private void Excute(UIKeyCommand keyCommand)
        {
            // Find
        }

        public override bool CanBecomeFirstResponder
        {
            get
            {
                return true; // Key commands require first responder
            }
        }
    }
}

Feedback?

Let us know!