Microsoft MVP성태의 닷넷 이야기
.NET Framework: 788. RawInput을 이용한 키보드/마우스 입력 모니터링 [링크 복사], [링크+제목 복사],
조회: 23844
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 10개 있습니다.)
Windows: 148. Windows - Raw Input의 Top level collection 의미
; https://www.sysnet.pe.kr/2/0/11612

.NET Framework: 788. RawInput을 이용한 키보드/마우스 입력 모니터링
; https://www.sysnet.pe.kr/2/0/11615

개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
; https://www.sysnet.pe.kr/2/0/12213

개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링
; https://www.sysnet.pe.kr/2/0/12215

.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기
; https://www.sysnet.pe.kr/2/0/12216

.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12218

.NET Framework: 917. C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12246

.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스
; https://www.sysnet.pe.kr/2/0/12469

.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법
; https://www.sysnet.pe.kr/2/0/12660

개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
; https://www.sysnet.pe.kr/2/0/12858




RawInput을 이용한 키보드/마우스 입력 모니터링

지난 글에서,

Windows - Raw Input의 Top level collection 의미
; https://www.sysnet.pe.kr/2/0/11612

Raw Input에 대한 이야기를 했는데요, 키에 대한 블록킹 기능은 없지만 모니터링을 하는 용도로는 잘 맞는 것 같습니다. 실제로 전역 후킹으로 인한 DLL 잠금 등의 문제가 없어 개발도 편리하고 C#에서도 구현하는 것이 매우 쉽습니다.

검색해 보면, 이미 대부분의 코드를 구현한 분이 있습니다. ^^

C# Get Mouse handle (GetRawInputDeviceInfo)
; https://stackoverflow.com/questions/14584280/c-sharp-get-mouse-handle-getrawinputdeviceinfo

실제로 다음과 같이 코딩해 봤습니다.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    // https://stackoverflow.com/questions/14584280/c-sharp-get-mouse-handle-getrawinputdeviceinfo
    public partial class Form1 : Form, IMessageFilter
    {
        public Form1()
        {
            InitializeComponent();
            Application.AddMessageFilter(this);
        }

        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == Win32Interop.WM_INPUT)
            {
                RawInput raw = Win32Interop.GetDeviceID(m);

                string source = (m.WParam.ToInt32() == Win32Interop.RIM_INPUT) ? "this" : "others";

                switch (raw.Header.Type)
                {
                    case RawInputType.Keyboard:
                        System.Diagnostics.Debug.WriteLine(
                            $"[{source}] [keyboard] Device ID : {raw.Header.Device}, VKey : {raw.Keyboard.VKey}, Code : {raw.Keyboard.MakeCode} Msg: {raw.Keyboard.Message}");
                        break;

                    case RawInputType.Mouse:
                        System.Diagnostics.Debug.WriteLine(
                            $"[{source}] [mouse] Device ID : {raw.Header.Device}, X : {raw.Mouse.LastX}, Y : {raw.Mouse.LastY}");
                        break;
                }
            }

            return false;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            Application.RemoveMessageFilter(this);
            base.OnFormClosing(e);
        }

        private unsafe void Form1_Load(object sender, EventArgs e)
        {
            RAWINPUTDEVICE [] Rid = new RAWINPUTDEVICE[2];

            Rid[0].UsagePage = HIDUsagePage.Generic;
            Rid[0].Usage = HIDUsage.Mouse;
            Rid[0].Flags = RawInputDeviceFlags.InputSink;
            Rid[0].WindowHandle = this.Handle;

            Rid[1].UsagePage = HIDUsagePage.Generic;
            Rid[1].Usage = HIDUsage.Keyboard;
            Rid[1].Flags = RawInputDeviceFlags.InputSink;
            Rid[1].WindowHandle = this.Handle;

            if (Win32Interop.RegisterRawInputDevices(Rid, 2, sizeof(RAWINPUTDEVICE)) == false)
            {
                MessageBox.Show("Failed to register");
            }
        }
    }
}

등록 부분을 보면,

Rid[0].UsagePage = HIDUsagePage.Generic;
Rid[0].Usage = HIDUsage.Mouse;
Rid[0].Flags = RawInputDeviceFlags.InputSink;
Rid[0].WindowHandle = this.Handle;

Rid[1].UsagePage = HIDUsagePage.Generic;
Rid[1].Usage = HIDUsage.Keyboard;
Rid[1].Flags = RawInputDeviceFlags.InputSink;
Rid[1].WindowHandle = this.Handle;

키보드와 마우스에 대한 입력을 모니터링하는 걸로 했고, Flags에 InputSink 옵션을 줬는데 이 옵션이 없으면 모니터링하는 프로그램이 전경(foreground) 윈도우로 선택되지 않으면 이벤트를 받지 못합니다. 즉, 다른 프로그램에 입력 포커스가 간 경우에도 모니터링을 원한다면 InputSink 옵션을 주는 것인데, 이 경우 시스템에게 어떤 윈도우에게 메시지를 전송할지 WindowHandle 속성에 Message Loop를 실행하고 있는 윈도우의 핸들을 설정해 주는 것으로 알려줄 수 있습니다.

등록이 정상적으로 되면, Window의 메시지 루프로 WM_INPUT 메시지를 통해 전달이 됩니다.

if (m.Msg == Win32Interop.WM_INPUT)
{
    RawInput raw = Win32Interop.GetDeviceID(m);

    string source = (m.WParam.ToInt32() == Win32Interop.RIM_INPUT) ? "this" : "others";

    switch (raw.Header.Type)
    {
        case RawInputType.Keyboard:
            System.Diagnostics.Debug.WriteLine(
                $"[{source}] [keyboard] Device ID : {raw.Header.Device}, VKey : {raw.Keyboard.VKey}, Code : {raw.Keyboard.MakeCode} Msg: {raw.Keyboard.Message}");
            break;

        case RawInputType.Mouse:
            System.Diagnostics.Debug.WriteLine(
                $"[{source}] [mouse] Device ID : {raw.Header.Device}, X : {raw.Mouse.LastX}, Y : {raw.Mouse.LastY}");
            break;
    }
}

따라서 WM_INPUT 이벤트가 들어온 경우, 위와 같이 키보드/마우스 유형에 따라 적절하게 정보를 구하면 됩니다. 해보면, keydown/keyup, mouse down/move/up의 모든 입력을 받아오는 것을 확인할 수 있습니다.

참고로, UAC 권한에 의해 일반 사용자 권한으로 위의 프로그램을 실행한 경우 관리자 권한으로 실행한 프로그램의 입력은 감지할 수 없습니다. 당연히, 관리자 권한의 프로그램에 대한 입력도 받고 싶다면 자신의 프로그램도 관리자 권한으로 실행해야 합니다.

(첨부 파일은 이 글의 프로젝트를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/19/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 91  92  93  [94]  95  96  97  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11616정성태7/17/201819451Graphics: 9. Unity Shader - 전역 변수의 초기화
11615정성태7/17/201823844.NET Framework: 788. RawInput을 이용한 키보드/마우스 입력 모니터링파일 다운로드1
11614정성태7/17/201826712Graphics: 8. Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표
11613정성태7/16/201823166Graphics: 7. Unity로 실습하는 Shader (5) - Flat Shading
11612정성태7/16/201821243Windows: 148. Windows - Raw Input의 Top level collection 의미
11611정성태7/15/201821622Graphics: 6. Unity로 실습하는 Shader (4) - 퐁 셰이딩(phong shading)
11610정성태7/15/201818973Graphics: 5. Unity로 실습하는 Shader (3) - 고로 셰이딩(gouraud shading) + 퐁 모델(Phong model) + Texture
11609정성태7/15/201821958Graphics: 4. Unity로 실습하는 Shader (2) - 고로 셰이딩(gouraud shading) + 퐁 모델(Phong model)
11608정성태7/15/201825716Graphics: 3. Unity로 실습하는 Shader (1) - 컬러 반전 및 상하/좌우 뒤집기
11607정성태7/14/201826049Graphics: 2. Unity로 실습하는 Shader [1]
11606정성태7/13/201826848사물인터넷: 19. PC에 연결해 동작하는 자신만의 USB 장치 만들어 보기파일 다운로드1
11605정성태7/13/201823242사물인터넷: 18. New NodeMCU v3 아두이노 호환 보드의 내장 LED 및 입력 핀 사용법 [1]파일 다운로드1
11604정성태7/12/201822216Math: 47. GeoGebra 기하 (24) - 정다각형파일 다운로드1
11603정성태7/12/201817504Math: 46. GeoGebra 기하 (23) - sqrt(n) 제곱근파일 다운로드1
11602정성태7/11/201818029Math: 45. GeoGebra 기하 (22) - 반전기하학의 원에 관한 반사변환파일 다운로드1
11601정성태7/11/201821120Math: 44. GeoGebra 기하 (21) - 반전기하학의 직선 및 원에 관한 반사변환파일 다운로드1
11600정성태7/10/201819740Math: 43. GeoGebra 기하 (20) - 세 점을 지나는 원파일 다운로드1
11599정성태7/10/201818627Math: 42. GeoGebra 기하 (19) - 두 원의 안과 밖으로 접하는 직선파일 다운로드1
11598정성태7/10/201820861Windows: 147. 시스템 복구 디스크를 USB 디스크에 만드는 방법
11597정성태7/10/201823126사물인터넷: 17. Thinary Electronic - ATmega328PB 아두이노 호환 보드의 개발 환경 구성
11596정성태7/10/201820451기타: 72. 과거의 용어 설명 - OWIN
11595정성태7/10/201825958사물인터넷: 16. New NodeMCU v3 아두이노 호환 보드의 기본 개발 환경 구성
11594정성태7/8/201820910Math: 41. GeoGebra 기하 (18) - 원의 중심 및 접선파일 다운로드1
11593정성태7/8/201820046Math: 40. GeoGebra 기하 (17) - 각의 복사파일 다운로드1
11591정성태7/7/201819068Math: 39. GeoGebra 기하 (16) - 삼각형의 방심과 방접원파일 다운로드1
11590정성태7/7/201818857Math: 38. GeoGebra 기하 (15) - 삼각형의 수심파일 다운로드1
... 91  92  93  [94]  95  96  97  98  99  100  101  102  103  104  105  ...