Pressing Control + key  
Author Message
kastanienreis





PostPosted: Visual C# General, Pressing Control + key Top

Hi

I want my application to accept keyboard input such as Control + p (pressed at the same time).

That's what I found:

bool modifier = false;

void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)

{

if ((ModifierKeys & Keys.Control) != 0)

modifier = true;

}

void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

{

if (modifier && e.KeyChar == 'p')

{

Console.WriteLine("control + p pressed");

modifier = false;

}

}

The problem with this example: pressing Control + p at the same time does not work.

What do I need to do

Thanks



Visual C#6  
 
 
Paul Louth





PostPosted: Visual C# General, Pressing Control + key Top

Set KeyPreview to true on the Form.

 And then use this method to test:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.Modifiers == Keys.Control)
   {
       if (e.KeyValue == (int)Keys.P)
       {
           MessageBox.Show("Ctrl+P pressed");
       }
   }
}


 
 
Sivavenkat17





PostPosted: Visual C# General, Pressing Control + key Top

kastanienreis,

Really didnt have time to do the r & d stuff. However, here is the key. When the modifier keys are pressed, the value of e.KeyChar is getting changed from the actual character value to an ascii value. Upon conversion of this value to an integer, a number that represents the alphabet in their order is got. i.e. If modifier key and the charecter 'A' or 'a' (case-insensitive) is pressed the number that is obtained is 1 and for 'B' (or 'b') is 2 and so on. So for 'P' it is 16.

So jus modify your code in

Form1_KeyPress

as below,

int pressKeyNum = Convert.ToInt32(e.KeyChar);
if(modifier && pressKeyNum == 16)
{
Console.WriteLine("ctrl + p is now Pressed");
modifier = false;
}

Hope this makes u smile!!!

Cheers,
Venkat


 
 
Udhaya Kumar D





PostPosted: Visual C# General, Pressing Control + key Top

A simple way to achieve that............

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyValue == 80) && (e.Control))
{
MessageBox.Show("Ctrl + p is now Pressed");
}
}