Use “SetWindowsHookEx” to hook into keyboard input events and does the keystroke logg

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Parul123
    New Member
    • Oct 2014
    • 4

    Use “SetWindowsHookEx” to hook into keyboard input events and does the keystroke logg

    I am using “SetWindowsHook Ex” to hook into keyboard input events and does the keystroke...

    Code:
    [StructLayout(LayoutKind.Sequential)]
        public class KeyboardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
    
        public class WindowsHookHelper
        {
            public delegate IntPtr HookDelegate(
                Int32 Code, IntPtr wParam, IntPtr lParam);
    
            [DllImport("User32.dll")]
            public static extern IntPtr CallNextHookEx(
                IntPtr hHook, Int32 nCode, IntPtr wParam, IntPtr lParam);
    
            [DllImport("User32.dll")]
            public static extern IntPtr UnhookWindowsHookEx(IntPtr hHook);
    
            [DllImport("User32.dll")]
            public static extern IntPtr SetWindowsHookEx(
                Int32 idHook, HookDelegate lpfn, IntPtr hmod,
                Int32 dwThreadId);
        }
    
        // Implement the IService service contract in a service class.
        public class KeyStrokeFileSavedService : IKeyStrokeFileSavedService, IDisposable
        {
            public event EventHandler<EventArgs> KeyBoardKeyPressed;        
            //public event EventHandler KeyBoardKeyPressed;
    
            private WindowsHookHelper.HookDelegate keyBoardDelegate;
            private IntPtr keyBoardHandle;
            private const Int32 WH_KEYBOARD_LL = 13;
            private const Int32 WH_KEYBOARD = 2;
    
            private bool disposed;
    
            public KeyStrokeFileSavedService()
            {
                keyBoardDelegate = KeyboardHookDelegate
                    ;
                keyBoardHandle = WindowsHookHelper.SetWindowsHookEx(
                    WH_KEYBOARD, keyBoardDelegate, IntPtr.Zero, 0);
            }
    
    
            [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
            static extern void CopyMemory(string c, IntPtr lParam, uint len);
    
            public IntPtr KeyboardHookDelegate(Int32 Code, IntPtr wParam, IntPtr lParam)
            {
                if ((Code >= 0) && (KeyBoardKeyPressed != null))
                {
                    KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
    
                    if (KeyBoardKeyPressed != null)
                    {
                        char keyData = (char)MyKeyboardHookStruct.vkCode;
                        //preKeys.Add(keyData);
                        using (StreamWriter sw = new StreamWriter("EnteredKeyStrokes.txt"))
                        {
                            string ch = "hjhk";                      
                            sw.WriteLine("{0}", ch);
                            sw.WriteLine("{0}", keyData);
                        }
                    }
                }
                return WindowsHookHelper.CallNextHookEx(keyBoardHandle, Code, wParam, lParam);
    
     public void Dispose()
            {
                Dispose(true);
            }
    
            protected virtual void Dispose(bool disposing)
            {
                if (!disposed)
                {
                    if (keyBoardHandle != IntPtr.Zero)
                    {
                        WindowsHookHelper.UnhookWindowsHookEx(
                            keyBoardHandle);
                    }
                    disposed = true;
                }
            }
    
            ~KeyStrokeFileSavedService()
            {
                Dispose(false);
            }
        }
    Last edited by Frinavale; Oct 21 '14, 02:26 PM. Reason: Added the details posted in the title of the thread to the body of the thread to give context to the code posted. Also added code tags to the thread so that it is easier to read
  • Parul123
    New Member
    • Oct 2014
    • 4

    #2
    Hi, I am unable to write into the file. Please suggest where am i going wrong

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Parul123,

      I see no code that writes information to a file in the code that you posted.

      I'm not sure what your problem is?

      If you don't know how to write to a file then please check out the MSDN documentation for the System.IO Namespace. This namespace contains classes that let you work with directories and files. You will probably be most interested in checking out the documentation for the File Class that is part of the System.IO Namespace because it contains information about how to write to a file and if you scroll down near the bottom of the documentation you will even find a code example that demonstrates how to use the File class.

      -Frinny

      Comment

      • Parul123
        New Member
        • Oct 2014
        • 4

        #4
        Here is my updated Solution :
        Code:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Windows.Forms;
        using System.Runtime.InteropServices;
        using System.Reflection;
        using System.IO;
        
        namespace FinalImplementWCFService
        {
            public class KeyboardHook 
            {
                [StructLayout(LayoutKind.Sequential)]
                public struct KeyboardHookStruct
                {
                    public int vkCode;
                    public int scanCode;
                    public int flags;
                    public int time;
                    public int dwExtraInfo;
                }
        
                public delegate Int32 HookDelegate(Int32 Code, Int32 wParam, IntPtr lParam);
        
                [DllImport("User32.dll")]
                public static extern Int32 CallNextHookEx(IntPtr hHook, Int32 nCode, Int32 wParam, IntPtr lParam);
        
                [DllImport("User32.dll")]
                public static extern IntPtr UnhookWindowsHookEx(IntPtr hHook);
        
                [DllImport("User32.dll")]
                public static extern IntPtr SetWindowsHookEx(Int32 idHook, HookDelegate lpfn, IntPtr hmod, Int32 dwThreadId);
        
                [DllImport("user32")] 
                private static extern int GetKeyboardState(byte[] pbKeyState);
        
                [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                private static extern short GetKeyState(int vKey); 
         
                [DllImport("user32")] 
                private static extern int ToAscii( int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState); 
        
                public event KeyEventHandler KeyDown;
                public event KeyEventHandler KeyUp;
                public event KeyPressEventHandler KeyPress;
        
                private IntPtr hHook;
                private const Int32 WH_KEYBOARD_LL = 13;
                private const Int32 WH_KEYBOARD = 2;
                private const int WM_KEYDOWN = 0x100;
                private const int WM_KEYUP = 0x101;
                private const int WM_SYSKEYDOWN = 0x104;
                private const int WM_SYSKEYUP = 0x105;
        
                private const byte VK_SHIFT = 0x10;
                private const byte VK_CAPITAL = 0x14;
                private const byte VK_NUMLOCK = 0x90;
        
                private const byte VK_LSHIFT = 0xA0;
                private const byte VK_RSHIFT = 0xA1;
                private const byte VK_LCONTROL = 0xA2;
                private const byte VK_RCONTROL = 0x3;
                private const byte VK_LALT = 0xA4;
                private const byte VK_RALT = 0xA5; 
        
        
        
                //private HookDelegate keyBoardDelegate;
        
                public KeyboardHook()
                {
                    hHook = SetWindowsHookEx
                            (
                                WH_KEYBOARD_LL,
                                new HookDelegate(KeyboardHookProc), 
                                Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
                                0
                            ); 
                }
        
                private Int32 KeyboardHookProc(Int32 nCode, Int32 wParam, IntPtr lParam) 
                {  
                    bool handled = false; 
         
                    if (nCode > -1 && (KeyDown != null || KeyUp != null || KeyPress != null))
                    {  
                        KeyboardHookStruct keyboardHookStruct = 
                            (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
        
                         //Is Control being held down? 
                        bool control = ((GetKeyState(VK_LCONTROL) & 0x80) != 0) || 
                                        ((GetKeyState(VK_RCONTROL) & 0x80) != 0); 
        
                        // Is Shift being held down? 
                        bool shift = ((GetKeyState(VK_LSHIFT) & 0x80) != 0) || 
                                        ((GetKeyState(VK_RSHIFT) & 0x80) != 0); 
        
                        // Is Alt being held down? 
                        bool alt = ((GetKeyState(VK_LALT) & 0x80) != 0) || 
                                    ((GetKeyState(VK_RALT) & 0x80) != 0); 
        
                        // Is CapsLock on? 
                        bool capslock = (GetKeyState(VK_CAPITAL) != 0); 
        
                        // Create event using keycode and control/shift/alt values found above 
                        KeyEventArgs e = new KeyEventArgs( 
                            (Keys)( 
                                keyboardHookStruct.vkCode | 
                                (control ? (int)Keys.Control : 0) | 
                                (shift ? (int)Keys.Shift : 0) | 
                                (alt ? (int)Keys.Alt : 0) 
                                )); 
        
                        // Handle KeyDown and KeyUp events 
                        switch (wParam) 
                        { 
        
                            case WM_KEYDOWN: 
                            case WM_SYSKEYDOWN: 
                                if (KeyDown != null) 
                                { 
                                    KeyDown(this, e); 
                                    handled = handled || e.Handled; 
                                } 
                                break; 
                            case WM_KEYUP: 
                            case WM_SYSKEYUP: 
                                if (KeyUp != null) 
                                { 
                                    KeyUp(this, e); 
                                    handled = handled || e.Handled; 
                                } 
                                break; 
                        } 
        
         
                        // Handle KeyPress event 
                        if(wParam == WM_KEYDOWN && !handled &&  !e.SuppressKeyPress && KeyPress != null) 
                        {  
                            byte[] keyState = new byte[256]; 
                            byte[] inBuffer = new byte[2]; 
                            GetKeyboardState(keyState); 
                                 
                            if (ToAscii(keyboardHookStruct.vkCode, keyboardHookStruct.scanCode, keyState, inBuffer, keyboardHookStruct.flags) == 1) 
                            { 
                                     
                                char key = (char)inBuffer[0]; 
                                if ((capslock ^ shift) && Char.IsLetter(key))  
                                    key = Char.ToUpper(key); 
                                KeyPressEventArgs e2 = new KeyPressEventArgs(key); 
                                KeyPress(this, e2); 
                                handled = handled || e.Handled;  
                            }  
                        }  
                    } 
         
                    if (handled) 
                    { 
                        return 1; 
                    } 
                    else 
                    { 
                        return CallNextHookEx(hHook, nCode, wParam, lParam); 
                    } 
         
                }
        
                static void Implement_KeyPress(object source, KeyPressEventArgs e)
                {
                    using (StreamWriter sw = new StreamWriter("EnteredKeyStrokes.txt"))
                    {
                        char pressedCharacter = e.KeyChar;
                        sw.WriteLine("{1} ", pressedCharacter);
                        sw.WriteLine("{1}","abc");
                    }
                }
        
                ~KeyboardHook() 
                {                 
                    // Stop Hook 
                    if (hHook != IntPtr.Zero) 
                    { 
                        UnhookWindowsHookEx(hHook); 
                    }  
                } 
        
            }
        }
        
        
        
        Windows Service : 
        
            static class Program
            {
                /// <summary>
                /// The main entry point for the application.
                /// </summary>
                static void Main()
                {
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[] 
        			{ 
        				new Service1() 
        			};
                    Console.WriteLine("Hello ");
                    ServiceBase.Run(ServicesToRun);
                }
            }
        Last edited by Frinavale; Oct 29 '14, 01:04 PM. Reason: Added code tags.

        Comment

        • Parul123
          New Member
          • Oct 2014
          • 4

          #5
          Kindly help out
          its not working

          Comment

          Working...