Solved

KeyUp and down event in c#

Posted on 2013-01-17
14
715 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 48

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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 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

11 Experts available now in Live!

Get 1:1 Help Now