DWinProgramming /Samples/Extra/HookSample2/HookSample2.d

Language D Lines 293
MD5 Hash 7d607f1263386b941ff5792584c38945
Repository git://github.com/AndrejMitrovic/DWinProgramming.git View Raw File View Project SPDX
  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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/+
 + Copyright (c) Charles Petzold, 1998.
 + Ported to the D Programming Language by Andrej Mitrovic, 2011.
 +/

module HookSample2;

import core.runtime;
import core.thread;
import std.conv;
import std.exception;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.utf : count, toUTFz;

auto toUTF16z(S)(S s)
{
    return toUTFz!(const(wchar)*)(s);
}

pragma(lib, "gdi32.lib");
import win32.winbase;
import win32.windef;
import win32.winuser;
import win32.wingdi;

alias std.algorithm.min min;
alias std.algorithm.max max;

// http://nehe.gamedev.net/article/msdn_virtualkey_codes/15009/

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    int result;
    void exceptionHandler(Throwable e) { throw e; }

    try
    {
        Runtime.initialize(&exceptionHandler);
        result = myWinMain(hInstance, hPrevInstance, lpCmdLine, iCmdShow);
        Runtime.terminate(&exceptionHandler);
    }
    catch (Throwable o)
    {
        MessageBox(null, o.toString().toUTF16z, "Error", MB_OK | MB_ICONEXCLAMATION);
        result = 0;
    }

    return result;
}

__gshared HHOOK keyHook;

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow)
{
    //~ keyHook = enforce(SetWindowsHookEx(WH_KEYBOARD,
                      //~ &KeyboardProc,
                      //~ cast(HINSTANCE)null,    // DLL handle, must be null for current thread handlers
                      //~ GetCurrentThreadId())); // Thread ID, or 0 if used for all desktop threads

    keyHook = enforce(SetWindowsHookEx(WH_KEYBOARD_LL,
                      &LowLevelKeyboardProc,
                      cast(HINSTANCE)null,    // DLL handle, must be null for current thread handlers
                      0));  // Thread ID, or 0 if used for all desktop threads. Must be 0 for LowLevel hook.


    string appName = "KeyView1";

    HWND hwnd;
    MSG  msg;
    WNDCLASS wndclass;

    wndclass.style         = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc   = &WndProc;
    wndclass.cbClsExtra    = 0;
    wndclass.cbWndExtra    = 0;
    wndclass.hInstance     = hInstance;
    wndclass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wndclass.hbrBackground = cast(HBRUSH) GetStockObject(WHITE_BRUSH);

    wndclass.lpszMenuName  = NULL;
    wndclass.lpszClassName = appName.toUTF16z;

    if (!RegisterClass(&wndclass))
    {
        MessageBox(NULL, "This program requires Windows NT!", appName.toUTF16z, MB_ICONERROR);
        return 0;
    }

    hwnd = CreateWindow(appName.toUTF16z,              // window class name
                        "Keyboard Message Viewer #1",  // window caption
                        WS_OVERLAPPEDWINDOW,           // window style
                        CW_USEDEFAULT,                 // initial x position
                        CW_USEDEFAULT,                 // initial y position
                        CW_USEDEFAULT,                 // initial x size
                        CW_USEDEFAULT,                 // initial y size
                        NULL,                          // parent window handle
                        NULL,                          // window menu handle
                        hInstance,                     // program instance handle
                        NULL);                         // creation parameters

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

extern(Windows)
LRESULT WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static int cLinesMax, cLines;
    static int cxClientMax, cyClientMax, cxClient, cyClient, cxChar, cyChar;
    static MSG[] msgArr;
    static int msgCount;
    static RECT rectScroll;

    enum szTop = "Message        Key       Char     Repeat Scan Ext ALT Prev Tran";
    enum szUnd = "_______        ___       ____     ______ ____ ___ ___ ____ ____";
    enum szFormat = ["%-13s %3s %-15s%1s%6s %4s %3s %3s %4s %4s",
                     "%-13s            0x%04X%1s%s %6s %4s %3s %3s %4s %4s"];
    enum szYes  = "Yes";
    enum szNo   = "No";
    enum szDown = "Down";
    enum szUp   = "Up";
    enum szMessage =
    [
        "WM_KEYDOWN",    "WM_KEYUP",
        "WM_CHAR",       "WM_DEADCHAR",
        "WM_SYSKEYDOWN", "WM_SYSKEYUP",
        "WM_SYSCHAR",    "WM_SYSDEADCHAR"
    ];

    HDC hdc;
    int iType;
    PAINTSTRUCT ps;
    string szBuffer;
    wchar[32] szKeyName;
    wchar[] keyName;
    int keyLength;
    TEXTMETRIC tm;

    switch (message)
    {
        case WM_CREATE:
        case WM_DISPLAYCHANGE:
        {
            // Get maximum size of client area
            cxClientMax = GetSystemMetrics(SM_CXMAXIMIZED);
            cyClientMax = GetSystemMetrics(SM_CYMAXIMIZED);

            hdc = GetDC(hwnd);
            scope(exit) ReleaseDC(hwnd, hdc);

            // Get character size for fixed-pitch font
            SelectObject(hdc, GetStockObject(SYSTEM_FIXED_FONT));
            GetTextMetrics(hdc, &tm);
            cxChar = tm.tmAveCharWidth;
            cyChar = tm.tmHeight;
            cLinesMax = cyClientMax / cyChar;
            cLines = 0;
            goto case WM_SIZE;
        }

        case WM_SIZE:
        {
            if (message == WM_SIZE)
            {
                cxClient = LOWORD(lParam);
                cyClient = HIWORD(lParam);
            }

            // Calculate scrolling rectangle
            rectScroll.left   = 0;
            rectScroll.right  = cxClient;
            rectScroll.top    = cyChar;
            rectScroll.bottom = cyChar * (cyClient / cyChar);

            InvalidateRect(hwnd, NULL, TRUE);
            return 0;
        }

        case WM_KEYDOWN:
        case WM_KEYUP:
        case WM_CHAR:
        case WM_DEADCHAR:
        case WM_SYSKEYDOWN:
        case WM_SYSKEYUP:
        case WM_SYSCHAR:
        case WM_SYSDEADCHAR:
        {
            msgArr ~= MSG(hwnd, message, wParam, lParam);
            cLines = min(cLines + 1, cLinesMax);

            // Scroll up
            ScrollWindow(hwnd, 0, -cyChar, &rectScroll, &rectScroll);
            break;
        }

        case WM_PAINT:
        {
            hdc = BeginPaint(hwnd, &ps);
            scope(exit) EndPaint(hwnd, &ps);

            SelectObject(hdc, GetStockObject(SYSTEM_FIXED_FONT));
            SetBkMode(hdc, TRANSPARENT);
            TextOut(hdc, 0, 0, szTop.toUTF16z, szTop.count);
            TextOut(hdc, 0, 0, szUnd.toUTF16z, szUnd.count);

            foreach (index, myMsg; lockstep(iota(0, min(cLines, cyClient / cyChar - 1)), retro(msgArr)))
            {
                iType = myMsg.message == WM_CHAR ||
                        myMsg.message == WM_SYSCHAR ||
                        myMsg.message == WM_DEADCHAR ||
                        myMsg.message == WM_SYSDEADCHAR;


                keyLength = GetKeyNameText(myMsg.lParam, szKeyName.ptr, szKeyName.length);
                keyName = szKeyName[0..keyLength];

                szBuffer = format(szFormat[iType],
                                  szMessage[myMsg.message - WM_KEYFIRST],
                                  myMsg.wParam,
                                  (iType ? "" : keyName.dup),
                                  (iType ? to!string(cast(char*)&myMsg.wParam) : ""),
                                  LOWORD(myMsg.lParam),
                                  HIWORD(myMsg.lParam) & 0xFF,
                                  (0x01000000 & myMsg.lParam ? szYes  : szNo),
                                  (0x20000000 & myMsg.lParam ? szYes  : szNo),
                                  (0x40000000 & myMsg.lParam ? szDown : szUp),
                                  (0x80000000 & myMsg.lParam ? szUp   : szDown)
                );

                TextOut(hdc, 0, (cyClient / cyChar - 1 - index) * cyChar, szBuffer.toUTF16z, szBuffer.count);
            }

            return 0;
        }

        case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        }

        default:
    }

    return DefWindowProc(hwnd, message, wParam, lParam);
}

WORD[WORD] keyMap;
shared static this()
{
    // A => B
    keyMap[0x41] = 0x42;
}

extern(Windows)
LRESULT LowLevelKeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
    auto kbs = cast(KBDLLHOOKSTRUCT*)lParam;

    // generate a new message
    if (!(kbs.flags & LLKHF_INJECTED))
    {
        INPUT input;
        input.type = INPUT_KEYBOARD;
        input.ki.dwFlags = (wParam == WM_KEYDOWN) ? 0 : KEYEVENTF_KEYUP;

        stderr.writefln("kbs: %s", *kbs);

        //~ stderr.writefln("scancode: %s alt: %s, vk: %s", kbs.scanCode, kbs.flags & LLKHF_ALTDOWN, kbs.vkCode);

        // replace key
        input.ki.wVk = keyMap.get(cast(WORD)kbs.vkCode, cast(WORD)kbs.vkCode);

        SendInput(1, &input, INPUT.sizeof);
        return -1;
    }

    return CallNextHookEx(keyHook, code, wParam, lParam);
}
Back to Top