Hi, if I want to call connection() method when F1 is pressed, what is the correct code?
Thanks
Printable View
Hi, if I want to call connection() method when F1 is pressed, what is the correct code?
Thanks
Assuming you are using forms, what you need to do is create a function to handle the KeyDown event of the form. Inside that function you check to see which key was pressed, if the key is F1 then you call your function.
Code:
// Form constructor
public Form1()
{
// Register the event handler for the forms KeyDown event
this.KeyDown += new KeyEventHandler(form_KeyDown);
}
// Function that handles the KeyDown event
private void form_KeyDown(Object sender, KeyEventArgs e)
{
// Check which key was pressed
switch (e.KeyCode)
{
case Keys.F1: // If the F1 key was pressed call the Connection() function.
Connection();
break;
}
}
you will also need to set the "KeyPreview" property of the form to true for the form to handle keypresses.
Or alternatively (and my preferred approach) is to add a menu to the form.
Then create a menu item and set the shortcut key is F1.
This has the advantage of being self-documenting : the menu item is there for all to see (and use) and the F1 key is obvious (as it's listed in the menu when it's dropped down).
This is windows standard - shortcut keys nearly always have associated menu items. Unless we want to go back to the old DOS days, with keyboard overlays (remember them.... like for WordPerfect hehe).
Darwen.
P.S. You shouldn't use F1 as the shortcut key - this is the 'help' shortcut in windows.