How to do multiple key down in C# control + P for example

So I needed to set up an app to print when the user presses control+p. Seems fairly straight forward right, after all there are all kinds of multiple key press codes like this in the world ctrl + P is print, ctrl + F8 could be something else, etc. etc… I was shocked when I went looking on the net for a good way to implement this in C# .NET and found no good examples, so I made my own keydown event handler, so here it is.

private List<string>  pressedKeys = new List<string>();
private void ShellForm_KeyDown(object sender, KeyEventArgs e)
{
pressedKeys.Add(e.KeyValue.ToString());
bool x = pressedKeys.Contains(“80″); //P key

bool y = pressedKeys.Contains(“17″); //CTRL Key

if (x & y & pressedKeys.IndexOf(“80″)>pressedKeys.IndexOf(“17″)) // so it has to have P and CTRL and CTRL has to be before P
{
MessageBox.Show(“you pressed CNTRL+P good job stupid…”);
_btnPrint_Click(null, e);
pressedKeys.Clear();
}
int count = pressedKeys.Count;
if (count>2)
{
pressedKeys.Clear();
}

}

the message window was just for my benefit… gotta remember to take it out. Let me know if you see, or know of, a better way to do this.  The one thing i see missing is some sort of timer to limit the time between key presses. As it is now a user could press “Ctrl” and then wait any amount of time and press “P” and it would print.

Cheers,
Tim

Digg this     Create a del.icio.us Bookmark     Add to Newsvine

One Response to “How to do multiple key down in C# control + P for example”

  1. Tester Says:

    I really loved your code it helped me a lot but i found 1 logic error and got a little improvement.
    First pressed key has lesser Index.
    If count is 2 and the last one wasnt control it wont work correctly. Using “if(!y)” instead of yours solves that.

Leave a Reply

Have a Facebook account? Use it instead of registering.