Click to See Complete Forum and Search --> : Any example for keyboard pressdown event?


kevin shen
February 25th, 2004, 03:30 AM
How can i use the keyboard pressdown event? My application is when i press "enter" or any other key like "del""F1", i want my code to jump to do sth. How can i do that? Any example for that?

Thanks!



Kevin

anushreeg
February 25th, 2004, 04:34 AM
private void Key_Pressed(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar == 13)
{
this.Close();
}
}

above is the code which you can use ,in this i close my form in case Enter key is pressed.

kevin shen
February 27th, 2004, 01:52 AM
what about for those function key like "del' or "F1"........... i can not find any ascii code for that......???


Thanks!


Kevin

Andy Tacker
February 27th, 2004, 02:14 AM
the solution is little bit tacky :). Its for Virtual Key CAPS LOCK. you can similarly use it for any other virtual key.

If the Control.ModifierKeys doesn't address your issue, then use Platform Invoke and call GetKeyState directly.

Declare this class first:
[
ComVisibleAttribute(false),
SuppressUnmanagedCodeSecurityAttribute()
]

internal class NativeMethods
{
[DllImport("user32.dll", CharSet=CharSet.Auto,
ExactSpelling=true,
CallingConvention=CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
public static int HIWORD(int n)
{
return ((n >> 16) & 0xffff/*=~0x0000*/);
}
public static int LOWORD(int n)
{
return (n & 0xffff/*=~0x0000*/);
}
}
Then when you want to check if Caps is down or ON, call:
short state = NativeMethods.GetKeyState(0x14 /*VK_CAPTIAL*/);
bool capsKeyDown = NativeMethods.HIWORD(state);
bool capsKeyON = NativeMethods.LOWORD(state);

Norfy
February 27th, 2004, 03:22 AM
Or alternatively catch the KeyDown event instead:

private void MyForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.F1)
Console.WriteLine("F1");
else if (e.KeyCode == Keys.Enter)
Console.WriteLine("Enter");
else
Console.WriteLine(e.KeyCode);
}