
format PE GUI 4.0 DLL
entry DllMain

include 'win32a.inc'

section '.code' code readable executable

; BOOL WINAPI DllMain ( HINSTANCE hInstDll, DWORD fdwReason, LPVOID lpvReserved )

proc DllMain hInstDll,fdwReason,lpvReserved

	cmp	[fdwReason],DLL_PROCESS_ATTACH
	je	.attach

	cmp	[fdwReason],DLL_PROCESS_DETACH
	jne	.finish

  .detach:

	dec	[g_uRefCount]
	jnz	.finish

	cmp	[g_hKeyboardHook],NULL
	je	.no_hook

	invoke	UnhookWindowsHookEx,[g_hKeyboardHook]
	mov	[g_hKeyboardHook],NULL

  .no_hook:

	mov	[g_hInstDll],NULL
	mov	[g_hNotify],NULL
	jmp	.finish

  .attach:

	inc	[g_uRefCount]
	cmp	[g_uRefCount],1
	jne	.finish

	mov	eax,[hInstDll]
	mov	[g_hInstDll],eax

  .finish:

	mov	eax,1

	ret

endp

; LRESULT CALLBACK KeyboardProc ( INT nCode, WPARAM wParam, LPARAM lParam )

proc KeyboardProc nCode,wParam,lParam

	cmp	[nCode],0
	jl	.finish

	cmp	[g_hNotify],NULL
	je	.finish

	invoke	IsWindow,[g_hNotify]
	test	eax,eax
	jz	.finish

	invoke	SendMessage,[g_hNotify],[g_uMsgId],[wParam],[lParam]

  .finish:

	invoke	CallNextHookEx,[g_hKeyboardHook],[nCode],[wParam],[lParam]

	ret
endp

; BOOL SetKeyboardHook ( HWND hNotify, UINT uMsgId )

proc SetKeyboardHook hNotify,uMsgId

	invoke	IsWindow,[hNotify]
	test	eax,eax
	jz	.failure

	mov	eax,[hNotify]
	mov	[g_hNotify],eax

	mov	eax,[uMsgId]
	cmp	eax,WM_USER
	jl	.failure

	mov	[g_uMsgId],eax

	invoke	SetWindowsHookEx,WH_KEYBOARD,KeyboardProc,[g_hInstDll],0
	test	eax,eax
	jz	.failure

	mov	[g_hKeyboardHook],eax

  .success:

	mov	eax,1
	jmp	.finish

  .failure:

	xor	eax,eax

  .finish:

	ret
endp

section '.data' data readable writeable shareable

  g_hInstDll	  dd 0
  g_uRefCount	  dd 0
  g_hKeyboardHook dd 0
  g_hNotify	  dd 0
  g_uMsgId	  dd 0

section '.idata' import data readable

  library kernel32,'kernel32.dll',\
	  user32,'user32.dll'

  include 'api\kernel32.inc'
  include 'api\user32.inc'

section '.edata' export data readable

  export 'KBL.DLL',SetKeyboardHook,'SetKeyboardHook'

section '.reloc' fixups data discardable
