Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

KeyUp and down event in c#

Posted on 2013-01-17
14
Medium Priority
?
811 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 53

Accepted Solution

by:
Rgonzo1971 earned 1000 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

927 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