본문 바로가기
C#

08# 키보드 후킹

by NaHyungMin 2016. 5. 11.

2010년도에 만든 키보드 후킹 C# 버전


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
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 KeyboardHook
{
    public partial class frmMain : Form
    {
        private CKeyHook cKey;
 
        public frmMain()
        {
            InitializeComponent();
        }
 
        private void frmMain_Load(object sender, EventArgs e)
        {
            frmMain Form = this;
            cKey = new CKeyHook(ref Form);
        }
 
        private void btnHookStart_Click(object sender, EventArgs e)
        {
            cKey.InstallHook();
        }
 
        private void btnHookStop_Click(object sender, EventArgs e)
        {
            cKey.UnistallHook();
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.Windows.Forms;
 
namespace KeyboardHook
{
    class CKeyHook
    {
#region "Keys"
        private const int WH_KEYBOARD_LL = 13;
        private const int GWL_HINSTANCE = -6;
        private const int HCBT_ACTIVATE = 5;
        private const int HCBT_CREATEWND = 3;
        private const int Enter = 13;
        private const int F1 = 112;
        private const int A = 65;
#endregion
        
#region  "DLL"
        private static IntPtr hookHandle;
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, MessageProc lpfn, IntPtr hMod, IntPtr dwThreadId);
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hHook);
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhook, int nCode, IntPtr wParam, KBDLLHOOKSTRUCT lParam);
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
 
        public delegate IntPtr MessageProc(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam);
 
        [MarshalAs(UnmanagedType.FunctionPtr)]
        MessageProc hookFunction;
 
        public struct KBDLLHOOKSTRUCT
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
 
       private frmMain TargetForm;
#endregion
 
#region  "Method"
       public CKeyHook(ref frmMain TargetForm)
        {
            this.TargetForm = TargetForm;
        }
 
        public void InstallHook()
        {
            hookFunction = new MessageProc(KeyboardCallback);
 
            //IntPtr hMod = System.Runtime.InteropServices.Marshal.GetHINSTANCE(this.GetType().Module );
 
            IntPtr hInstance = GetModuleHandle(null);
 
            //int hHandle =  Marshal.GetHINSTANCE(Assembly.GetCallingAssembly().GetModules()[0]).ToInt32();
 
            Console.WriteLine("hooked");
 
            //hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, IntPtr.Zero, new IntPtr(AppDomain.GetCurrentThreadId()));
            hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, hInstance, IntPtr.Zero);
            //hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, hMod, IntPtr.Zero);
        }
 
        public void UnistallHook()
        {
            bool hookCheck;
 
            hookCheck = UnhookWindowsHookEx(hookHandle);
 
            if (true == hookCheck)
            {
                Console.WriteLine("unhooked");
            }
            else
            {
                Console.WriteLine("unhooked fail");
            }
        }
 
        private IntPtr KeyboardCallback(int code, IntPtr wparam, ref KBDLLHOOKSTRUCT lparam)
        {
            try
            {
                //특수 키보드 에 해당 flags 값이 1이면 KEY_PRESS 이벤트  129이면 KEY_UP 이벤트
                //일반 키보드 에 해당 flags 값이 0이면 KEY_PRESS 이벤트  128이면 KEY_UP 이벤트
                if(lparam.flags == 0//키 타입
                {
                    switch (lparam.vkCode) //키 정보 입력
                    {
                        case Enter :
                            TargetForm.lblKey.Text = "Enter";
                            break;
                        case A :
                            TargetForm.lblKey.Text = "A";
                            break;
                        default:
                            TargetForm.lblKey.Text = lparam.vkCode.ToString();
                            break;
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
 
            IntPtr inPtr;
 
            try
            {
                inPtr = CallNextHookEx(hookHandle, code, wparam, lparam);
            }
            catch (System.Exception ex)
            {
 
                Console.WriteLine("NextHook: '" + ex);
                inPtr = new IntPtr(0);
            }
 
            return inPtr;
        }
#endregion
    }
}
 
cs


'C#' 카테고리의 다른 글

10# 데이터 압축  (0) 2017.05.19
09# 중복 없는 랜덤키 값 추출  (0) 2017.04.18
07# C# Entity framework  (0) 2016.05.11
06# 네트워크 활성화/비활성화  (0) 2016.05.11
05# 소켓 비동기식 처리  (0) 2016.04.18