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
Printable View
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
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.
what about for those function key like "del' or "F1"........... i can not find any ascii code for that......???
Thanks!
Kevin
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:
Then when you want to check if Caps is down or ON, call:Code:[
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*/);
}
}
Code:short state = NativeMethods.GetKeyState(0x14 /*VK_CAPTIAL*/);
bool capsKeyDown = NativeMethods.HIWORD(state);
bool capsKeyON = NativeMethods.LOWORD(state);
Or alternatively catch the KeyDown event instead:
Code: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);
}