|
-
Jan 11th, 2010, 04:35 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] Capture Multiple Key Presses
Hey guys!
I'm looking to trigger an event in my form that requires users to press a certain sequence of keys on my form, say red or blue. I'm unsure how to do this.
I know how to check for since key instances but not multiples so any help would be greatly appreciated as always.
Cheers.
-
Jan 11th, 2010, 07:15 PM
#2
Re: Capture Multiple Key Presses
You simply need to remember what's gone before, e.g.
csharp Code:
private int keyPresses = 0; private void Form1_KeyPress(object sender, KeyPressEventArgs e) { switch (e.KeyChar) { case 'a': // 'a' is always the first key in the sequence. this.keyPresses = 1; break; case 'b': // if 'b' follows 'a' then progress, otherwise start over. this.keyPresses = (this.keyPresses == 1 ? 2 : 0); break; case 'c': // if 'c' follows 'a' and 'b' then progress, otherwise start over. this.keyPresses = (this.keyPresses == 2 ? 3 : 0); break; case 'd': // if 'd' follows 'a', 'b' and 'c' then complete the sequence. if (this.keyPresses == 3) { MessageBox.Show("You pressed abcd!"); } // Start over. this.keyPresses = 0; break; default: // Start over on any other key. this.keyPresses = 0; break; } }
-
Jan 12th, 2010, 01:31 PM
#3
Thread Starter
Frenzied Member
Re: Capture Multiple Key Presses
That worked perfectly. I figured it would be something along those lines but I couldn't get it right. Looks like my more complex solution was at fault. Oh well.
Thanks!
Edit: If anyone is interested here is the code I used. it's a slightly modified version of the one above and should give more customizability.
csharp Code:
private Dictionary<int, char> secret_code = new Dictionary<int, char>() { {0, 't'}, {1, 'e'}, {2, 's'}, {3, 't'} }; private void frmMain_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == secret_code[key_presses]) { if (key_presses == (secret_code.Count() - 1)) { this.key_presses = 0; MessageBox.Show("You sound the secret!", "Congratulations!", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ++this.key_presses; } } else { this.key_presses = 0; } }
Last edited by sciguyryan; Jan 12th, 2010 at 02:57 PM.
Reason: Added code.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|