Here an example of how I managed to solve this issue in Xamarin Forms.
// A model to store the values of the key event.
public class KeyEventArgs : EventArgs
{
public bool IsAltKeyPressed { get; set; }
public string Key { get; set; }
}
// UWP Custom render
public class MyPageViewRenderer : PageRenderer
{
/// <summary>
/// Monitor windows core ui keypress when MyPageView is showing
/// </summary>
public MyPageViewRenderer() : base()
{
// When ExplorePage appears then attach to the ui core keydown event
Loaded += (object sender, RoutedEventArgs e) =>
{
CoreWindow.GetForCurrentThread().Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
};
// When ExplorePage disappears then detach from the ui core keydown event
Unloaded += (object sender, RoutedEventArgs e) =>
{
CoreWindow.GetForCurrentThread().Dispatcher.AcceleratorKeyActivated -= Dispatcher_AcceleratorKeyActivated;
};
}
private void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
if ((args.EventType == CoreAcceleratorKeyEventType.KeyDown || args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown)
&& !args.KeyStatus.WasKeyDown)
{
bool isAltKeyPressed = args.KeyStatus.IsMenuKeyDown;
(Element as MyPageView).MyPageView_KeyPressed(Element, new KeyEventArgs { IsAltKeyPressed = isAltKeyPressed, Key = args.VirtualKey.ToString() });
}
}
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyPageView : ContentPage
{
public MyPageView()
{
InitializeComponent();
this.Focus();
}
public void MyPageView_KeyPressed(object sender, KeyEventArgs e)
{
(this.BindingContext as MyPageViewModel).CommandOnKeyPress?.Execute(e);
}
}