1

How could I use MAUI to create a keydown event? Also, we know there is no direct view for us to use keydown or keyup, but I have researched handler mappers in nativeview (Android) or using render, but the details of how to implement them are unclear.Or are there other ways to get a keydown event in MAUI? Thanks

I develop a zebra app; there is an entry for scan, so it needs a keydown event (maybe you will say we could use textchanged; actually, I have tried, and it worked, but there are some other problems, not good, such as selecting text, because my entry also has another function, which is to input a number like an id, then key 'enter' to get codbarre; the second function is scanning; so problem here is that I need a condition to control input; its mean id length could not more than 13 (codebarre); another problem of textchange is that when I scan the same codbare again, it will not select all text) so keydown will be a perfect solution, but how to get keydwon event in Maui?

simone
  • 21
  • 6

2 Answers2

1

we can call ModifyEntry() everywhere(in constructor) we want;

  //#region out constructor

void ModifyEntry()
  {
   Microsoft.Maui.Handlers.EntryHandler.Mapper
   .AppendToMapping("MyCustomization",(handler, view) =>
       { 

  #if ANDROID   
 //remove Entry underline

handler.PlatformView.Background = null;
handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
        //keyboard,keydown,keyup event
        handler.PlatformView.KeyPress += (sender, e) =>
        {
            try
            {
                if (e.KeyCode == Android.Views.Keycode.Tab || e.KeyCode == 
             Android.Views.Keycode.Enter)
                {e.Handled = true;

                    if ((e.KeyCode == Android.Views.Keycode.Enter) && _prodottiStorage.List(Content) != null)
                    {//when press key Enter selectall
                        ((Entry)handler.VirtualView).CursorPosition = 0;
                        ((Entry)handler.VirtualView).SelectionLength = ((Entry)handler.VirtualView).Text != null ? ((Entry)handler.VirtualView).Text.Length : 0;
                    }
                    if ((e.KeyCode == Android.Views.Keycode.Enter) && (e.Event.Action == Android.Views.KeyEventActions.Up))
                    {//your codes here:

                        prodottis.Clear();

                        if (_prodottiStorage.ListId(Content) == null)
                        {

                            prodottis.Clear();
                            Content = null;

                        }

                        if (_prodottiStorage.ListId(Content) != null)
                        {
                            foreach (var p in _prodottiStorage.ListId(Content))
                            {

                                prodottis.Add(p); Content = p.CodBarre;
                                ((Entry)handler.VirtualView).CursorPosition = 0;
                                ((Entry)handler.VirtualView).SelectionLength = ((Entry)handler.VirtualView).Text != null ? ((Entry)handler.VirtualView).Text.Length : 0;

                                if (p.CodBarre == string.Empty | p.CodArticolo == 0) { return; }
                            }

                            prodottis.Clear();

                            if (_prodottiStorage.List(Content) == null)
                            {

                                prodottis.Clear();
                                Content = null;

                            }

                            if (_prodottiStorage.List(Content) != null)
                            {
                                p = _prodottiStorage.List(Content);
                                prodottis.Add(p);
                                if (p.CodBarre == string.Empty | p.CodArticolo == 0) { prodottis.Clear(); }
                            }
                        }

                    }
                }
                else

                    e.Handled = false;
            }
            catch (Exception Ex)
            {
            }
        };
    #endif
    });
}#endregion

here : https://learn.microsoft.com/en-us/dotnet/maui/user-interface/handlers/customize

simone
  • 21
  • 6
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 31 '23 at 13:05
  • To be honest, I totally agree with this BOT. This is what we need, something official for citations and documentations. Instead of having to rely mostly on the community solutions. – H.A.H. May 31 '23 at 14:08
  • H.A.H nice to meet you ,see you again here – simone May 31 '23 at 14:41
1

I hope this helps:

  1. Create a class that implements interface Android.Views.View.IOnKeyListener and define a relevant delegate:
#if ANDROID
using Android.Runtime;
using Android.Views;
#endif

namespace MyNamespace;

#if ANDROID
/// <summary>
/// A delegate for a listener function to handle key events.
/// </summary>
/// <param name="v">The view that received the key event.</param>
/// <param name="keyCode">The code of the pressed key.</param>
/// <param name="e">Extra information about the key event.</param>
/// <returns>True if the listener function has consumed the event, false otherwise.</returns>
public delegate bool OnKeyDelegate(Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e);

public class KeyListener : Java.Lang.Object, Android.Views.View.IOnKeyListener
{
    /// <value>
    /// The function that will handle the key events.
    /// </value>
    private readonly OnKeyDelegate OnKeyDelegate;

    /// <summary>
    /// Sets the function that will handle the key events.
    /// </summary>
    /// <param name="onKeyDelegate"></param>
    public KeyListener(OnKeyDelegate onKeyDelegate)
    {
        OnKeyDelegate = onKeyDelegate;
    }

    /// <summary>
    /// Calls the specified listener function to handle the key events.
    /// </summary>
    /// <param name="v">The view that received the key event.</param>
    /// <param name="keyCode">The code of the pressed key.</param>
    /// <param name="e">Extra information about the key event.</param>
    /// <returns>True if the listener function has consumed the event, false otherwise.</returns>
    public bool OnKey(Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
        if (OnKeyDelegate == null) return false;

        return OnKeyDelegate(v, keyCode, e); // true will intercept keyboard clicks
    }
}
#endif
  1. In the page with your barcode entry (named "BarcodeEntry", for example), define this function:
    /// <summary>
    /// Set controls' key handlers.
    /// </summary>
    private void SetKeyHandler()
    {
#if ANDROID
        if ((BarcodeEntry != null) && (BarcodeEntry.Handler != null))
            (BarcodeEntry.Handler.PlatformView as AppCompatEditText).SetOnKeyListener(new KeyListener(OnBarcodeEntryKey));
#endif
    }
  1. Define the keyboard handler function for the entry (the example handles only Escape and Down-Arrow keys):
#if ANDROID
    /// <summary>
    /// A listener function to handle the key events.
    /// </summary>
    /// <param name="v">The view that received the key event.</param>
    /// <param name="keyCode">The code of the pressed key.</param>
    /// <param name="e">Extra information about the key event.</param>
    /// <returns>True if the listener function has consumed the event, false otherwise.</returns>
    private bool OnBarcodeEntryKey(Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
        if (e.Action == KeyEventActions.Down)
            switch (keyCode)
            {
                case Keycode.DpadDown:
                    // Your code here
                    return true;

                case Keycode.Escape: 
                    // Your code here
                    return true;

                default: 
                    return false;
            }

        return false;
    }
#endif
  1. Last (but very important), add a call to SetKeyHandler() function to the Load event of page with barcode entry:
    /// <summary>
    /// Initializes page on loading.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments.</param>
    private void Page_Loaded(object sender, EventArgs e)
    {
        SetKeyHandlers();

        // Your code here
    }
rentoulis
  • 184
  • 6