Solved

KeyUp and down event in c#

Posted on 2013-01-17
14
768 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
14 Comments
 
LVL 52

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

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 86

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
 
LVL 86

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 86

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 86

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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

627 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