CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 4 of 4

Thread: How To Use KeyPressed

  1. #1
    Join Date
    Mar 2009

    How To Use KeyPressed

    Hi, if I want to call connection() method when F1 is pressed, what is the correct code?


  2. #2
    Join Date
    Jul 2006

    Re: How To Use KeyPressed

    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.

            // 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.

  3. #3
    Join Date
    Nov 2007
    .NET 3.5 / VS2008 Developer

    Re: How To Use KeyPressed

    you will also need to set the "KeyPreview" property of the form to true for the form to handle keypresses.

  4. #4
    Join Date
    Jan 2002
    Scaro, UK

    Re: How To Use KeyPressed

    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).


    P.S. You shouldn't use F1 as the shortcut key - this is the 'help' shortcut in windows.
    Last edited by darwen; August 9th, 2009 at 05:11 PM. - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)