Results 1 to 6 of 6

Thread: [2.0] How Do I Capture Key Events From The Arrow keys?

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2006
    Posts
    41

    Smile [2.0] How Do I Capture Key Events From The Arrow keys?

    Hello everybody,

    I have been trying to figure out how to capture input from the arrow keys, but I'm not having any luck. I first checked my copy of C# - How To Program for the section on keyboard event handling, but after reading the relevant section I'm still having problems as I'm not really sure what was being done and that's also true of some of the examples I googled for. Basically I want 4 different methods to be called - one for each arrow key when the user presses it.

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    namespace TestApplication
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            //How Do I Call These 4 Methods?
            private void UpArrow()
            {
                //Do something when the UP arrow is pressed   
            }
    
            private void DownArrow()
            {
                //Do something when the DOWN arrow is pressed   
            }
    
            private void LeftArrow()
            {
                //Do something when the LEFT arrow is pressed   
            }
    
            private void RightArrow()
            {
                //Do something when the RIGHT arrow is pressed   
            }
    
        }
    }

    Thanks for taking the time to read my post.

    Regards,


    The Thing.
    Using: VB.net + C#.net 2005 Express Editions + .Net Framework 2.0

    ~ Man Is The Warmest Place To Hide ~

  2. #2
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    Re: [2.0] How Do I Capture Key Events From The Arrow keys?

    Hi there,
    First, set your form's KeyPreview property to true. Then you can handle your form's KeyDown or KeyUp event. Check the key that was pressed and follow appropriately.

    c# Code:
    1. private void Form1_KeyDown(object sender, KeyEventArgs e)
    2. {
    3.     switch (e.KeyCode)
    4.     {
    5.         case Keys.Up:
    6.             DoUpKey();
    7.             break;
    8.  
    9.         case Keys.Down:
    10.             DoDownKey();
    11.             break;
    12.  
    13.         // Etcetera, etcetera.                
    14.     }
    15. }
    16.  
    17. private void DoUpKey()
    18. {
    19.     MessageBox.Show("Up");
    20. }
    21.  
    22. private void DoDownKey()
    23. {
    24.     MessageBox.Show("Down");
    25. }

  3. #3
    Hyperactive Member BramVandenbon's Avatar
    Join Date
    Jan 2002
    Location
    Belgium
    Posts
    502

    Re: [2.0] How Do I Capture Key Events From The Arrow keys?

    Quote Originally Posted by nmadd
    Hi there,
    First, set your form's KeyPreview property to true. Then you can handle your form's KeyDown or KeyUp event. ...
    wow, that's nice ? Does this really work? Even when the focus is inside one of the controls such as a textbox?

    I fixed this problem in a lot more complex way using a messagefilter or somethng like that. ... maybe I'll post it later.
    ____________________________________________

    Please rate my messages. Thank you!
    ____________________________________________
    Bram Vandenbon
    http://www.bramvandenbon.com

  4. #4
    Hyperactive Member BramVandenbon's Avatar
    Join Date
    Jan 2002
    Location
    Belgium
    Posts
    502

    Re: [2.0] How Do I Capture Key Events From The Arrow keys?

    I just wanted to add this messagefilter code sample. Just in case the other way doesn't work. This is how I did it, when I needed it.

    A messagefilter can process all messages of the application. ("What kind of messages might that be?", you may wonder: mouse clicks and mouse movements, keys being pressed, ... .)

    You can activate the filter as followed
    Code:
    Application.AddMessageFilter(filter);
    Of course first of all you need a filter or you can't do that. That filter must implement the IMessageFilter interface. This interface subscribes the PreFilterMessage function.
    Code:
        class HotKeyManager : IMessageFilter
        {
            public bool PreFilterMessage(ref Message m)
            {
                // we'll change this later ;-)
                return false;
            }
        }
    What should the function look like ? You don't need to go through all messages. You only need those of the 0x100 type (which means that the message is about pressed keys).
    Code:
            public bool PreFilterMessage(ref Message m)
            {
                Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
                if (m.Msg == 0x100)
                {
                    //we'll add code later here.
                }
                return false;
            }
    By the way, the return value of this function determines wether or not the key should still be progressed afterwards by for example a textfield or so which has the focus. ...

    To finish it off, I created a singleton class of it which executes itself.
    Code:
        class HotKeyManager : IMessageFilter
        {
            private static HotKeyManager _singleton = null;
    
            static public HotKeyManager GetInstance()
            {
                if (_singleton != null)
                {
                    _singleton = new HotKeyManager();
                }
                return _singleton
            }
    
            private HotKeyManager(){
                Application.AddMessageFilter(filter);
            }
    
            public bool PreFilterMessage(ref Message m)
            {
                Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
                if (m.Msg == 0x100)
                {
                    //we'll add code later here.
                }
                return false;
            }
        }

    Next I guess it would be nice to throw an event when a key is pressed so...
    Code:
        class HotKeyManager : IMessageFilter
        {
            private static HotKeyManager _singleton = null;
            public event KeyEventHandler KeyPressed;
    
            static public HotKeyManager GetInstance()
            {
                if (_singleton != null)
                {
                    _singleton = new HotKeyManager();
                }
                return _singleton
            }
    
            private HotKeyManager()
            {
                Application.AddMessageFilter(filter);
            }
    
            protected void OnKeyPressed(KeyEventArgs e)
            {
                 if (KeyPressed != null){
                     KeyPressed(this, e);
                 }    
            }
    
            public bool PreFilterMessage(ref Message m)
            {
                Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
                if (m.Msg == 0x100)
                {
                    KeyEventArgs e = new KeyEventArgs(keyCode);
                    OnKeyPressed(e)
                }
                return false;
            }
        }
    And to finish it REALLY off I guess you could add an Enabled property so that you can turn it off and on . This can come in handy when you are REALLY typing text and not some kind of codes.

    How to use it
    First you initialize it and you bnd the eventhandler to it.
    Code:
    HotKeyManager manager = HotKeyManager.GetInstance();
    manager.KeyPressed += new KeyEventsHandler(HotKeyManager_KeyPressed);
    And off course you need a function that handles the events.
    Code:
    private void HotKeyManager_KeyPressed(object sender, KeyEventArgs e){
        if (e.KeyCode == Keys.MouseUp){
            //do something ... or you can use a switch too of course !
        }
    }
    And off course you can use a switch instead of an if. The eventargs also has information about the Shift and Alt keys being pressed and stuff like that which might come in handy.

    I hope this was useful, but if the nmadd-way works, then of course you don't need all this junk I wrote here, hehe :-D
    ____________________________________________

    Please rate my messages. Thank you!
    ____________________________________________
    Bram Vandenbon
    http://www.bramvandenbon.com

  5. #5
    New Member
    Join Date
    Jul 2007
    Posts
    11

    Re: [2.0] How Do I Capture Key Events From The Arrow keys?

    Go to the events of the form (lightning bolt next to properties) click in the KeyUp one and press enter...it'll take you to the code...then make it look like this:

    Code:
            private void Form1_KeyUp(object sender, KeyEventArgs e)
                {
                if (e.KeyCode == Keys.Down) //same applies for all keys
                    MessageBox.Show("You just pressed the down key!");
                }

  6. #6
    Fanatic Member daimous's Avatar
    Join Date
    Aug 2005
    Posts
    657

    Re: [2.0] How Do I Capture Key Events From The Arrow keys?

    wow, that's nice ? Does this really work? Even when the focus is inside one of the controls such as a textbox?
    Indeed. It really works..

Posting Permissions

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



Click Here to Expand Forum to Full Width