XNA - Keyboard text input

后端 未结 5 440
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 08:28

Okay, so basically I want to be able to retrieve keyboard text. Like entering text into a text field or something. I\'m only writing my game for windows. I\'ve disregarded u

5条回答
  •  心在旅途
    2020-12-29 09:09

    Here's a simple way, IMO, to have the space, back, A-Z and then the special chars !,@,#,$,%,^,&,*,(,). (Note, you need to import System.Linq) Here are the fields:

    Keys[] keys;
    bool[] IskeyUp;
    string[] SC = { ")" , "!", "@", "#", "$", "%", "^", "&", "*", "("};//special characters
    

    Constructor:

    keys = new Keys[38];
    Keys[] tempkeys;
    tempkeys = Enum.GetValues(typeof(Keys)).Cast().ToArray();
    int j = 0;
    for (int i = 0; i < tempkeys.Length; i++)
    {
        if (i == 1 || i == 11 || (i > 26 && i < 63))//get the keys listed above as well as A-Z
        {
            keys[j] = tempkeys[i];//fill our key array
            j++;
        }
    }
    IskeyUp = new bool[keys.Length]; //boolean for each key to make the user have to release the key before adding to the string
    for (int i = 0; i < keys.Length; i++)
        IskeyUp[i] = true;
    

    And Finally, the update method:

    string result = "";
    
    public override void Update(GameTime gameTime)
    {
        KeyboardState state = Keyboard.GetState();
        int i = 0;
        foreach (Keys key in keys)
        {
            if (state.IsKeyDown(key))
            {
                if (IskeyUp[i])
                {
                    if (key == Keys.Back && result != "") result = result.Remove(result.Length - 1);
                    if (key == Keys.Space) result += " ";
                    if (i > 1 && i < 12)
                    {
                        if (state.IsKeyDown(Keys.RightShift) || state.IsKeyDown(Keys.LeftShift))
                            result += SC[i - 2];//if shift is down, and a number is pressed, using the special key
                        else result += key.ToString()[1];
                    }
                    if (i > 11 && i < 38)
                    {
                        if (state.IsKeyDown(Keys.RightShift) || state.IsKeyDown(Keys.LeftShift))
                           result += key.ToString();
                        else result += key.ToString().ToLower(); //return the lowercase char is shift is up.
                    }
                }
                IskeyUp[i] = false; //make sure we know the key is pressed
            }
            else if (state.IsKeyUp(key)) IskeyUp[i] = true;
            i++;
        }
        base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
    }
    

    Hopefull this well help. I personally thought it was easier to use than the hooks, and this also can easily be modified for special results (such as shuffling the keys).

提交回复
热议问题