C# - Global hook

By , 11/25/2012
(0 ratings)
This is an example code to catch a keypress. In this example the 'ALT'-key is catched.

You will need the class 'Utilities': http://dotnet-snippets.com/dns/globalhook-class-SID659.aspx

Author: Jakob Lis, translation by Michael List
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;
using Utilities;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        globalKeyboardHook hook = new globalKeyboardHook();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            hook.HookedKeys.Add(Keys.Alt);
        }

        private void timerhook_Tick(object sender, EventArgs e)
        {
            hook.KeyDown += new KeyEventHandler(hook_KeyDown); //Key being pressed
            hook.KeyUp += new KeyEventHandler(hook_KeyUp); //Key being released
        }

        void hook_KeyDown(object sender, KeyEventArgs e)
        {
            //Your code
            e.Handled = true;
        }

        void hook_KeyUp(object sender, KeyEventArgs e)
        {
            //Your code
            e.Handled = true;
        }

    }
}
Tagged with hook, global hook, keydown, key, press, keyboard.

Comments

 

Log in, to comment!