Microsoft MVP성태의 닷넷 이야기
Windows: 148. Windows - Raw Input의 Top level collection 의미 [링크 복사], [링크+제목 복사],
조회: 12895
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 9개 있습니다.)
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

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




Windows - Raw Input의 Top level collection 의미

오호~~~ 아래와 같은 질문이 있는데,

windows7 C# SetWindowHookex
; https://social.msdn.microsoft.com/Forums/ko-KR/27e36513-c0b6-4bb0-8525-5a4ce00fa7cf/windows7-c-setwindowhookex?forum=visualcsharpko

저도 처음 알았습니다. Windows 7에는,

Global hooks getting lost on Windows 7
; https://learn.microsoft.com/en-us/archive/blogs/alejacma/global-hooks-getting-lost-on-windows-7

다음의 제약이 있습니다.

On Windows 7 we have to make sure that the callback function of the hook can return in less than LowLevelHooksTimeout, which is 300 ms. And we allow for the application to be timed out 10 times when processing the hook callback message. If it times out an 11th time, Windows will unhook the application from the hook chain. This is a by design feature and it was added in Win7 RTM.


시나리오가 그려지는군요. ^^ SetWindowsHookEx을 마련해놨는데, 응용 프로그램 개발자들이 그것의 구현을 잘못하게 되면 시스템의 키보드/마우스의 반응이 함께 느려지는 것입니다. 사용자들은, 어떤 응용 프로그램이 SetWindowsHookEx를 사용하고 있는지 알 수 없으므로 결국에는 윈도우 운영체제의 결함으로 느끼게 되는 것입니다. 아마도... 이런 상황을 더는 두고 볼 수가 없었겠지요. 그래서 윈도우 운영체제가 HOOKPROC 콜백 함수를 호출했을 때 300ms 이상 지연되는 횟수가 11회까지 되면 해당 HOOK을 제거한다는 것입니다.




이와 함께, SetWindowsHookEx보다는 Raw Input을 이용한 방법을 추천하고 있습니다. 물론, 그 둘 간의 차이는 있습니다. SetWindowsHookEx는 키보드 입력 시 응용 프로그램에 전달하지 못하도록 막는 것도 가능하지만, Raw Input 관련 기술의 경우 막는 것까지는 안 되고, 모니터링은 가능하다는 것입니다.

어쨌든, 모니터링 정도만 원한다면 굳이 SetWindowsHookEx보다는 Raw Input을 사용하는 것은 좋은 의도로 보입니다.

Using Raw Input
; https://learn.microsoft.com/en-us/windows/desktop/inputdev/using-raw-input

그런데 위의 사용법에 보면 usUsagePage와 usUsage 속성에 넣는 값이 좀 낯섭니다.

RAWINPUTDEVICE Rid[2];
        
Rid[0].usUsagePage = 0x01; 
Rid[0].usUsage = 0x02; 
Rid[0].dwFlags = RIDEV_NOLEGACY;   // adds HID mouse and also ignores legacy mouse messages
Rid[0].hwndTarget = 0;

Rid[1].usUsagePage = 0x01; 
Rid[1].usUsage = 0x06; 
Rid[1].dwFlags = RIDEV_NOLEGACY;   // adds HID keyboard and also ignores legacy keyboard messages
Rid[1].hwndTarget = 0;

if (RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE) {
    //registration failed. Call GetLastError for the cause of the error
}

관련 구조체의 도움말을 보면,

RAWINPUTDEVICE structure
; https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-rawinputdevice

usUsagePage - Top level collection Usage page for the raw input device. 
usUsage - Top level collection Usage for the raw input device. 

* TLC(top level collection)

더 낯설어서 별로 도움이 안 됩니다. ^^ 어쨌든, 예제 코드를 통해 다음의 설정으로 정리가 됩니다.

HID mouse
    usUsagepage = 0x01
    usUsage = 0x02

HID keyboard
    usUsagepage = 0x01
    usUsage = 0x06

game pad
    usUsagepage = 0x01
    usUsage = 0x05

joystick
    usUsagepage = 0x01
    usUsage = 0x04

그런데, 보고 있자니 다음의 글이 생각납니다.

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
; https://www.sysnet.pe.kr/2/0/11363

위의 글에서 HID 장치에 대한 Report Descriptors를 작성한 것이 나오는데요, 바로 여기에 USAGE_PAGE와 USAGE가 있습니다.

05, 01, USAGE_PAGE (Generic Desktop)
09, 06, USAGE (Keyboard)
a1, 01, COLLECTION (Application)
...[생략]...
C0      END_COLLECTION

05, 01  USAGE_PAGE (Generic Desktop)
09, 02  USAGE (Mouse)
a1, 01  COLLECTION (Application)
...[생략]...
C0      END_COLLECTION

아하... 그러니까 위에서도 키보드인 경우 USAGE_PAGE == 1, USAGE == 6을 지정했고 마우스인 경우 USAGE_PAGE는 같고 USAGE 값이 2입니다. 정확히 일치하는군요. 결국 저 값들에 대한 정보는 다음의 문서에서 구할 수 있습니다.

Top-Level Collections
; https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections

Top-Level Collections Opened by Windows for System Use
; https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections-opened-by-windows-for-system-use




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







[최초 등록일: ]
[최종 수정일: 4/29/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13435정성태11/6/20232939닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232726스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232449스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232531오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232897스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232739닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233015닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233096닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233302닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233461스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233233닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233212스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233351닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233435닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235674스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233257스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233952닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233486닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233285오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233786닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233553디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233743닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237040닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233535Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235071닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233914닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...