Guide Text Entry in Windows Phone
/
The layout may not be perfect, but it is a lot easier than writing your own text input.
Some of our students are making quite a good job of Evil Squash. There are even a few Windows Phone versions out there, which is nice. One of the things that the game must do is ask the player for their name. Anyone who is using XNA for the game has a problem here, as text entry in XNA can be non-trivial. Unless you use the XNA Guide.
The Guide is a way that you can ask the user questions and do lots of other interesting things. I used it to write a silly program that asks the user for their name.
if (text.Length == 0) { if (!Guide.IsVisible) { // display the guide Guide.BeginShowKeyboardInput(PlayerIndex.One, "Name entry", // title for the page "Enter your name", // question for user "Fred", // default text new AsyncCallback(gotText), // callback method this); // object reference } }
This is the code that I wrote. It is part of the Update method. The variable text is going to hold the name that the user enters. If it is empty I must display the guide to read it. The first thing I do is to check that the guide is not already visible. If it is I don’t need to display it again. Remember that Update is called 30 times a second on the phone, I don’t want to be overwhelmed by loads of guides.
The BeginShowGuide puts the guide on the screen. The first three parameters make very good sense, the last two are a bit more confusing. The fourth parameter gives the Guide the method to call when the user has finished typing in their name and pressed OK to close the Guide down. The fifth parameter just needs to be a reference to an object that can identify the request. I’ve given it the value of this, which is a reference to the current game. The result of this method call is that the guide is displayed, as you can see in the screenshot at the top.
When the user closes the guide, either by pressing ok or cancel, the Guide will call the gotText method that I told it about:
void gotText(IAsyncResult result) { if (result.IsCompleted) { text = Guide.EndShowKeyboardInput(result); if (text == null) { // user pressed cancel text = "Cancelled"; } } }
This checks to see if the request is completed. If it is the method gets the text from the Guide by calling EndShowKeyboardInput. If the user pressed cancel the Guide will return a null string. The code above sets the text to Cancelled, otherwise the text is left as whatever the user typed in.
My program just draws the name string on the screen:
You can find a sample project with this code in it here.