Riccardo Pezzolati
Riccardo Pezzolati

Reputation: 359

Intercept global event Xamarin Forms

In MainActivity.cs I have this method

public override bool OnKeyUp(Keycode keyCode, KeyEvent e)
    {
        if (keyCode.ToString().Equals("F1"))
        {
            App.Left = true;
            App.Right = false;
        }
        else if (keyCode.ToString().Equals("F2"))
        {
            App.Left = false;
            App.Right = true;
        }
        else
        {
            App.Left = false;
            App.Right = false;
        }
        return base.OnKeyUp(keyCode, e);
    }

In my Page class, how can I constantly check whether left or right are true and in case trigger an event?

Upvotes: 0

Views: 459

Answers (1)

Umair M
Umair M

Reputation: 10720

  1. Create a plugin using Dependency Service and your shared interface should look like this:

    public interface IKeyEvent
    {
        event Action<KeyResult> OnKeyEvent;
    }
    
    public enum KeyResult {None, Left, Right};
    
  2. Implement this for different platforms (Android/iOS/UWP) accordingly and bind it to PCL project. (Check dependency service implementation for help)

  3. Link it to platform-specific KeyUp event.

for android it would be like this:

Droid.KeyEventHandler

[assembly: Dependency(typeof(KeyEventHandler))]
namespace YourNameSpace.Droid
{
    public class KeyEventHandler : IKeyEvent 
    {
        public static KeyEventHandler Current;

        public KeyEventHandler()
        {
            Current = this;
        }

        public event Action<KeyResult> OnKeyResult;


        public void RaiseKeyEvent(KeyResult key)
        {
            OnKeyResult?.Invoke(key);            
        }
    }
}

MainActivity

public override bool OnKeyUp(Keycode keyCode, KeyEvent e)
{
    KeyResult keyResult = KeyResult.None; // need to reference YourNameSpace.Shared project to use this enum
    if (keyCode == KeyCode.A)
    {
        keyResult = KeyResult.Left;
    }
    else if (keyCode == KeyCode.D))
    {
        keyResult = KeyResult.Right;
    }
    else
    {
        keyResult = KeyResult.None;
    }

    if (KeyEventHandler.Current != null)
    {
        KeyEventHandler.Current.RaiseKeyEvent(keyResult);
    }

    return base.OnKeyUp(keyCode, e);
}

NOTE: Left and right keys are mapped to A and D of physical keyboard respectively, for some reason my Macbook's F1/F2 keys were not registering to simulator so I used A/D.

Hope this helps :)

Upvotes: 1

Related Questions