I’ve seen a few queries of how to get text input into an XNA game on Windows Phone 7 – so I thought I’d show you how.
It is all very simple. All you need to do is call Guide.BeginShowKeyboardInput. This uses the IAsync pattern to provide asynchronous input to game play. To get the string result from the input ‘dialog’ you call Guide.EndShowKeyboardInput putting the output into a string variable and passing in your IAsync Result object.
The code for my simple demo is below:
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if(!Guide.IsVisible) if(input=="") Guide.BeginShowKeyboardInput (PlayerIndex.One,"Enter a string","Hello world",".",delegate(IAsyncResult result) { input = Guide.EndShowKeyboardInput(result); }, null); // TODO: Add your update logic here base.Update(gameTime); } The key line (excuse pun) is:
Guide.BeginShowKeyboardInput (PlayerIndex.One,"Enter a string","Hello world",".",delegate(IAsyncResult result) { input = Guide.EndShowKeyboardInput(result); }, null);
I’m using an anonymous method to implement the callback. This purely puts the result of Guide.EndShowKeyboardInput into the app level public string ‘input’.
I check for Guide.IsVisible because I am calling the Guide in the Update method for this demo – this gets called every 1/30th of a second. I only collect one input.