Skip to content Skip to sidebar Skip to footer

Open On-screen Keyboard For Xamarin/monogame

I'm developing a game using Xamarin/Monogame and I need to open the keyboard on a mobile device when they click on my input control. I recognize that I can capture input using Keyb

Solution 1:

After much digging I was able to figure out the solution. I'll first start by explaining how I got there: I stopped thinking "how do I display the on-screen keyboard in Mono?" and started thinking "how do you display the keyboard on an Android device?" This lead me to this article which was perfect; Xamarin and Android. Here's the relevant snippets:

Showing the soft input (on-screen keyboard)

var pView = game.Services.GetService<View>();
var inputMethodManager =Application.GetSystemService(Context.InputMethodService) asInputMethodManager;
inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);

Some key notes about this:

  • The View class is Android.Views.View
  • The InputMethodManager class is Android.Views.InputMethods.InputMethodManager
  • This code is called from within an Activity class, so Application refers to a property on that class (this.Application)
  • game is your game class (in Mono) that is of type Microsoft.Xna.Framework.Game

Hiding the soft input (on-screen keyboard)

InputMethodManager inputMethodManager = Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
inputMethodManager.HideSoftInputFromWindow(pView.WindowToken, HideSoftInputFlags.None);

After I solved this, the way I was capturing input (the XNA/Mono way) was not capturing this input. So I had to continue digging. While it doesn't necessarily pertain to this question, I'd like to post it here so it exists somewhere. This documentation on the Android Developers site helped me.

To capture input directly (which is what we need to do to capture to OSK input), you need to override the OnKeyPress method on the activity your game is running in. For me, this looks as follows:

publicclassAndroidActivity : AndroidGameActivity
{
    privatevoidOnKeyPress(object sender, View.KeyEventArgs e)
    {
        // do stuff with the input
    }
}

Hope this helps anyone else who got stuck with this; the information was hard to find, but now that I've changed my frame of mind to "how does Android/iOS handle this thing" I've been able to locate answers more easily. Good luck!

Post a Comment for "Open On-screen Keyboard For Xamarin/monogame"