Search code examples
xamarin.formsxamarin.androidkeypress

How to Simulate or Trigger Enter or Return key programmatically in Xamarin.Forms


I have a camera scanner app that scans barcodes and the result is returned to an Entry field.

I can focus that Entry field but I can't get it to press enter programmatically, is there a way to do this in Xamarin.Forms?

My Target platform is Android.


Solution

  • this is a small replication of the problem, which is fairly simple.

    in XAML:

    <Entry Name="entry" Completed="OnCompleted"/>
    <Label Name="label"/>
    <Button Text="PRESS ENTER" Clicked="OnButtonPressed"/>
    

    in C# or code behind I have:

    void OnCompleted(object sender, EventArgs e) 
    {
        label.Text = entry.Text;
    }
    
    void OnButtonPressed (object sender, EventArgs e)
    {
        // we will be adding this code here at the last step
    }
    

    then create an Interface because the only easy way to do this is by using the native android functionality through a DependencyService:

    public Interface IEnterService
    {
        void PressEnter();
    }
    

    Then in the Android Project you need to create a class for example: EnterService and implement the previous created interface like this:

    [assembly: Xamarin.Forms.Dependency(typeof(EnterService))]
    namespace TestEnterPressed.Droid
    {
        [Register("sendKeyDownUpSync", "(I)V", "GetSendKeyDownUpSync_IHandler")]
        class EnterService : IEnterService
        {
            public void PressEnter()
            {
                Console.WriteLine("ENTER IS PRESSED");
                Instrumentation inst = new Instrumentation();
                new Thread(() =>
                {
                    Thread.CurrentThread.IsBackground = true;
                    
                    /* run your code here */
                    inst.SendKeyDownUpSync(Keycode.Enter);
                }).Start();
            }
        }
    }
    

    Then in the last step use your DependencyService to simulate Enter pressed through a button other than the keyboard or after scanning a barcode with a camera you can do it like this:

    void OnButtonPressed(object sender, EventArgs e)
    {
        entry.Focus();
        DependencyService.Get<IEnterService>().PressEnter();
    }
    

    I hope this is useful to somebody, thanks a bunch everyone :)