How to detect complex keypress (STRG+N, P)?

  • Thread starter =?ISO-8859-15?Q?Roland_M=FCller?=
  • Start date
?

=?ISO-8859-15?Q?Roland_M=FCller?=

Hello,

i know how to get a simple keyboard combination, but how to detect a
combination of keyboard combination, pressing STRG+N and P?
This does not work:

private void MdiParentForm_KeyDown(object sender, KeyEventArgs e) {
Debug.WriteLine(e.KeyData);

switch(e.KeyData) {
case Keys.Control|Keys.N|Keys.P:
MessageBox.Show("test");
break;
}
}

Any help?
Thanks in advance, Roland!
 
G

Guest

Hi Roland,

You cannot check for multiple keypresses with a single operation. In the
Keys enumeration, letter keys do not have "Flag" values that can be OR'd
together, such as Keys.N | Keys.P. In this case, Keys.N = 78 and Keys.P =
80. Only the modifier keys such as Keys.Shift can be OR'd with letter keys,
such as Keys.Shift | Keys.N.

Instead, to detect a complex key sequence, you need to save the state of the
keypress then check that state on the next keypress. For example:

private Keys m_PreviousKey;
private void MdiParentForm_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyData)
{
case Keys.Control|Keys.N:
Console.WriteLine( "First key" );
break;
case Keys.P:
if (this.m_PreviousKey == Keys.Control|Keys.N)
Console.WriteLine( "GOT IT!" );
break;
}
this.m_PreviousKey = e.KeyData;
}
 
G

Guest

Thanks, that is easy and logical.

Mini-Tools Timm said:
Hi Roland,

You cannot check for multiple keypresses with a single operation. In the
Keys enumeration, letter keys do not have "Flag" values that can be OR'd
together, such as Keys.N | Keys.P. In this case, Keys.N = 78 and Keys.P =
80. Only the modifier keys such as Keys.Shift can be OR'd with letter keys,
such as Keys.Shift | Keys.N.

Instead, to detect a complex key sequence, you need to save the state of the
keypress then check that state on the next keypress. For example:

private Keys m_PreviousKey;
private void MdiParentForm_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyData)
{
case Keys.Control|Keys.N:
Console.WriteLine( "First key" );
break;
case Keys.P:
if (this.m_PreviousKey == Keys.Control|Keys.N)
Console.WriteLine( "GOT IT!" );
break;
}
this.m_PreviousKey = e.KeyData;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top