Solved

KeyUp and down event in c#

Posted on 2013-01-17
14
743 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 50

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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
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

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!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VS 2017 18 108
Change Locale for Crystal Reports Dynamically in VB.Net 2010 Winforms. 3 35
Need help converting bitmap to image in VB.Net 8 46
Asp.Net Session Question 2 36
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…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

726 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