Solved

KeyUp and down event in c#

Posted on 2013-01-17
14
719 Views
Last Modified: 2013-06-06
I need to get event in c# window based application, when control, shift or alt is press or up.
I need to perform certain event when any of control, shift or alt is press down and up.
Can u give me any in build event handler with C#?
0
Comment
Question by:sachinjain_aspnet
14 Comments
 
LVL 49

Accepted Solution

by:
Rgonzo1971 earned 500 total points
ID: 38786899
Hi,

This could help

private void MyExampleButton_Click(object sender, RoutedEventArgs e)
{
    if ((Keyboard.Modifiers & ModifierKeys.Control) > 0) {
        System.Diagnostics.Debug.WriteLine("Control is pressed");
    } else {
        System.Diagnostics.Debug.WriteLine("Control is NOT pressed");
    }
}

Open in new window

Regards
0
 
LVL 12

Expert Comment

by:HugoHiasl
ID: 38786909
Every Control has Events for

KeyDown
KeyPressed
KeyUp


Usage like in this sample:

private void Form1_Load(object sender, EventArgs e)
{
    this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}

void Form1_KeyUp(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.NumPad1:
            break;
        case Keys.NumPad2:
            break;
            //...
    }
}
0
 
LVL 9

Expert Comment

by:sognoct
ID: 38786928
public Form1()
    {
      InitializeComponent();
      this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.me_KeyDown);
    }

    public void me_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
        
          if (e.Control) {
            MessageBox.Show("Control pressed");
                      }
          if (e.Alt )
          {
            MessageBox.Show("Alt pressed");
          }
          if (e.Shift )
          {
            MessageBox.Show("Shift pressed");
          }  
        }

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38787268
If you need a global event, across all forms, then use IMessageFilter:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Application.AddMessageFilter(new MyFilter());
        }

    }

    public class MyFilter : IMessageFilter
    {

        private const int WM_KEYUP = 0x101;
        private const int WM_KEYDOWN = 0x100;
        private const int WM_SYSKEYUP = 0x0105;
        private const int WM_SYSKEYDOWN = 0x0104;

        public bool PreFilterMessage(ref Message m)
        {
            Keys key = (Keys)(int)m.WParam & Keys.KeyCode;
            switch (m.Msg)
            {
                case WM_KEYDOWN:
                case WM_SYSKEYDOWN:
                    switch (key)
                    {
                        case Keys.ControlKey:
                            Console.WriteLine("Ctrl Down");
                            break;

                        case Keys.ShiftKey:
                            Console.WriteLine("Shift Down");
                            break;

                        case Keys.Menu:
                            Console.WriteLine("Alt Down");
                            break;

                    }
                    break;

                case WM_KEYUP:
                case WM_SYSKEYUP:
                    switch (key)
                    {
                        case Keys.ControlKey:
                            Console.WriteLine("Ctrl Up");
                            break;

                        case Keys.ShiftKey:
                            Console.WriteLine("Shift Up");
                            break;

                        case Keys.Menu:
                            Console.WriteLine("Alt Up");
                            break;

                    }
                    break;
            }

            return false; // allow normal process of the keystroke
        }

    }

}

Open in new window


You can make "MyFilter" raise custom events that the form(s) subscribe to.
0
 

Author Comment

by:sachinjain_aspnet
ID: 38805030
In global event, it works, but my application should be selected.

I want when my application is in not selected, but running in task manager. Then handle events at modifier keys & win keys when up & down.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38805349
"I want when my application is in not selected"

In that case you want a low level keyboard hook via WH_KEYBOARD_LL.  Here's on example:
http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C
0
 

Author Comment

by:sachinjain_aspnet
ID: 38813730
I already implemented same, but it is not executing at client machine. So, does u have any other way to do that?
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38814117
You already implemented which approach?...
0
 

Author Comment

by:sachinjain_aspnet
ID: 38826481
keyboard hook via WH_KEYBOARD_LL ; approach
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38826708
Alright.  We'd have to see your code to make sure you integrated it into your project correctly.  =\
0
 

Author Comment

by:sachinjain_aspnet
ID: 38838391
a)      Declare a global variable :
UserActivityHook actHook;

b ) Make a function  :
private void ChkKeyPress()
        {
            actHook = new UserActivityHook(); // crate an instance with global hooks
            // hang on events
            //  actHook.OnMouseActivity += new MouseEventHandler(MouseMoved);
            actHook.KeyDown += new KeyEventHandler(MyKeyDown);
            // actHook.KeyPress += new KeyPressEventHandler(MyKeyPress);
            actHook.KeyUp += new KeyEventHandler(MyKeyUp);
        }
c)      Call ChkKeyPress(); in form_load()

d)      For Down and up function :
public void MyKeyDown(object sender, KeyEventArgs e)
        {
            if (clsMobileVariables.SendAppInfo == false)
                return;
           
            //   MessageBox.Show("hi");
            //    MessageBox.Show("MyKeyDown");
            string KeyPress = "";

            if (e.KeyData.ToString().ToLower().Contains("control"))
                KeyPress = KeyPress + "-Ctrl";
            if (e.KeyData.ToString().ToLower().Contains("shift"))
                KeyPress = KeyPress + "-Shift";
            if ((e.KeyData.ToString().ToLower().Contains("alt")) || (e.KeyData.ToString().ToLower().Contains("menu")))
                KeyPress = KeyPress + "-Alt/Option";
            if (e.KeyData.ToString().ToLower().Contains("win") && (WinPress == false))
                KeyPress = KeyPress + "-Win/CMD";
           



            if (!string.IsNullOrEmpty(KeyPress) && clsMobileVariables.networkStream != null)
            {
                KeyPress = "KeyPress" + KeyPress + "@";
                // MessageBox.Show(KeyPress);
               
                Byte[] sendBytes = Encoding.ASCII.GetBytes(KeyPress);
                MobileRemoteServer.SendKeyBoard(sendBytes, clsMobileVariables.networkStream);
              //  clsMobileVariables.DataSend.Append(KeyPress);
               // clsMobileVariables.DataSend.Append(System.Environment.NewLine);
                if (KeyPress.Contains("Win"))
                    WinPress = true;
            }

            // MessageBox.Show(KeyPress);
        }

        public void MyKeyUp(object sender, KeyEventArgs e)
        {
            if (clsMobileVariables.SendAppInfo == false)
                return;
            //      MessageBox.Show("MyKeyUp");
            string MesssageReleased = "";
            //if (e.KeyData.ToString().ToLower().Contains("control"))
            //{
            //    MesssageReleased = MesssageReleased + "-Ctrl";
            //   // clsMobileVariables.CheckKeyRelease = true;
            //}
            //else
            //{
            //    //clsMobileVariables.CheckKeyRelease = false;
            //}
            if (e.KeyData.ToString().ToLower().Contains("control"))
                MesssageReleased = MesssageReleased + "-Ctrl";
            if (e.KeyData.ToString().ToLower().Contains("shift"))
                MesssageReleased = MesssageReleased + "-Shift";
            if ((e.KeyData.ToString().ToLower().Contains("alt")) || (e.KeyData.ToString().ToLower().Contains("menu")))
                MesssageReleased = MesssageReleased + "-Alt/Option";
            if ((e.KeyData.ToString().ToLower().Contains("win")))
                MesssageReleased = MesssageReleased + "-Win/CMD";

            if (!string.IsNullOrEmpty(MesssageReleased) && clsMobileVariables.networkStream != null && clsMobileVariables.CheckKeyRelease == true)
            {
                MesssageReleased = "KeyReleased" + MesssageReleased + "@";
                Byte[] sendBytes = Encoding.ASCII.GetBytes(MesssageReleased);
                //   MessageBox.Show(MesssageReleased);
                clsMobileVariables.DataSend.Append(MesssageReleased);
                clsMobileVariables.DataSend.Append(System.Environment.NewLine);
                MobileRemoteServer.SendKeyBoard(sendBytes, clsMobileVariables.networkStream);
             
                if (MesssageReleased.Contains("Win"))
                    WinPress = false;
            }

            // MessageBox.Show(MesssageReleased);
        }
0
 

Author Comment

by:sachinjain_aspnet
ID: 38995495
Hello Expert exchange , does i did anything wrong for same ?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38995683
So that approach works on your machine but not the client machine?...
0
 

Author Comment

by:sachinjain_aspnet
ID: 39016912
Nope, it does not work proper in my machine also in window 2007 64 bit. It occurs, but if i press down  key 5-6 time or continuous press same key 5-6 seconds  , it stop to fire event.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now