Notifications
Clear all

[Closed] Keyboard or mouse global hook

Hi folks. I figured out how to get information from keyboard, mouse or any other input device accessible through directX.

I was most interested in mouse wheel. There was solution for this problem, but it was requiring to keep focus on specified dotnet control.

Here is the code:

device = undefined
timerObj = undefined

function onTimer =
(
	if device != undefined then
	(
		local wheelDelta = device.CurrentMouseState.Z / 120
		
		if wheelDelta != 0 then
			format "Mouse wheel rolled: %
" wheelDelta
	)
	else
		timerObj.stop()
)

function initialize =
(
	dotnet.loadAssembly "Microsoft.DirectX.DirectInput"

	local deviceList = (dotNetclass "Microsoft.DirectX.DirectInput.Manager").GetDevices (dotNetclass "Microsoft.DirectX.DirectInput.DeviceClass").pointer (dotNetclass "Microsoft.DirectX.DirectInput.EnumDevicesFlags").AttachedOnly

	if deviceList.MoveNext() then
	(
		device = dotNetobject "Microsoft.DirectX.DirectInput.Device" (deviceList.current.productguid)
		device.acquire()

		if timerObj == undefined then
		(
			timerObj = dotnetobject "System.Timers.Timer" (1000/10) autoreset:true -- 10 FPS timer
			dotnet.addEventHandler timerObj #elapsed onTimer	
		)

		timerObj.start()

		true -- return
	)
	else
	(
		device = undefined
		false -- return
	)
)

function finalize =
(
	if timerObj != undefined then
	(
		timerObj.stop()
		dotNet.removeAllEventHandlers timerObj
		timerObj.dispose()
		timerObj = undefined
	)

	if device != undefined then
	(
		device.unacquire()
		device.dispose()
		device = undefined
	)
)

-- test
initialize()

It works even while 3d max window loses focus or is minimized. So you may need to combine it with checking for focus, for cursor over viewport etc.

3 Replies

where is a hook?

Maybe not exactlty a hook, but way to capture global mouse events (so like-a-hook :)).

Is it possible to get callback when keyes/device updated, instead of using timer. I not found any events in dotnet for doing that.

1 Reply
(@denist)
Joined: 11 months ago

Posts: 0