问题
Can anyone point me in the right direction to be able to simulate sms style typing using keypress on the number pad?
I can get each number to print out a letter but am unsure of how to get my program to treat a number of keypresses on the same key as the same 'event' (i.e. scrolling through several letters if the key is pressed again within a period of (for example) 2 seconds).
I have looked up multiple keypresses but always come up with key combinations (ctrl, alt, delete etc).
回答1:
Firstly, you need to store the available combinations:
static char[] num1 = { 'A', 'B', 'C', '1' };
static char[] num2 = { 'D', 'E', 'F', '2' };
// etc...
And then we make a dictionary of the combinations, mapped to the right key character that produces them:
Dictionary<char, char[]> map = new Dictionary<char, char[]>()
{
{'1', num1},
{'2', num2}
};
Some variables to keep track:
char[] curr = null;
char currChar = '-';
int index = 0;
A printing function:
void Print()
{
Console.WriteLine(curr[index]);
}
And the logic:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (map.ContainsKey(e.KeyChar))
{
if (curr == null || e.KeyChar != currChar)
{
curr = map[e.KeyChar];
index = 0;
currChar = e.KeyChar;
Print();
}
else
{
++index;
if (index == curr.Length)
index = 0;
Print();
}
}
}
The logic basically checks to make sure our keymap contains the keycode in question. If we're not tracking anything, or if it's different to the one we're currently tracking, use that particular map and the first index.
Otherwise, if it's a repeat key-press, increase the index (looping back to the beginning if we pass the end).
回答2:
You need a state-machine and count the number of presses on each key to determine the letter. Then pass these letters on (using events) to the rest of your app.
Ps. did you notice that the numbers on a numeric keypad are in a different order than on a phone? (789 are the top row on a keyboard and the bottom row on a phone)
来源:https://stackoverflow.com/questions/7900597/simulating-sms-style-typing-using-keypress