I am developing a Xamarin.Forms application for iOS, Android and UWP.
I would like to hook into hardware keyboard
I needed to allow numeric input + an enter at the end in my XamForms app. Here's how I solved it in Xamarin Forms 3.0.0.482510 / Xamarin.iOS 11.10 (it's a little different than Kevin's answer above because I wanted to handle it in the XamForms shared xaml project, not in the iOS project):
In your iOS project (with a Xamarin Forms shared project in the solution named 'MobileProject' for example), create a new class:
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MobileProject.MainPage), typeof (com.YourCompany.iOS.KeyboardHookRenderer))]
namespace com.YourCompany.iOS
{
public class KeyboardHookRenderer : PageRenderer
{
private string _RecvValue = string.Empty;
public override bool CanBecomeFirstResponder
{
get { return true; }
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
string key = string.Empty;
var selector = new ObjCRuntime.Selector("KeyRecv:");
UIKeyCommand accelerator1 = UIKeyCommand.Create((NSString)"1", 0, selector);
AddKeyCommand(accelerator1);
UIKeyCommand accelerator2 = UIKeyCommand.Create((NSString)"2", 0, selector);
AddKeyCommand(accelerator2);
UIKeyCommand accelerator3 = UIKeyCommand.Create((NSString)"3", 0, selector);
AddKeyCommand(accelerator3);
... etc as many as you need or use a loop based on key id...
}
[Export("KeyRecv:")]
public void KeyRecv(UIKeyCommand cmd)
{
if (cmd == null)
return;
var inputValue = cmd.Input;
if (inputValue == "\n" || inputValue == "\r")
{
((MobileProject.MainPage) Element)?.HandleHardwareKeyboard(_RecvValue);
_RecvValue = string.Empty;
}
else
{
_RecvValue += inputValue;
}
}
}
}
Then, in your shared app in MainPage.xaml.cs, you just need:
///
/// Handle hardware keys (from KeyboardHookRender.cs in iOS project)
///
/// Keys sent, including trailing Cr or Lf
public void HandleHardwareKeyboard(string keys)
{
SomeTextbox.Text = keys;
// Whatever else you need to do to handle it
}