Search code examples
winapiluaffiluajit

If Left click ffi in lua


I'm new to ffi.

Basically I'm trying to get a bool when the mouse left button is clicked.

I've done some research and found something called WM_LBUTTONDOWN

However I don't know how to put it in ffi.cdef then getting a bool.


Solution

  • This program polls the mouse button state once per 1 ms and exits when LMB is pressed

    local ffi = require("ffi")
    ffi.cdef[[
       short GetAsyncKeyState(int vKey);
       void Sleep(int ms);
    ]]
    
    local function is_key_down(vKey)
       return ffi.C.GetAsyncKeyState(vKey) < 0
    end
    
    local function sleep(ms)
       ffi.C.Sleep(ms or 1)
    end
    
    local VK_LBUTTON  = 0x01 -- Left mouse button
    local VK_RBUTTON  = 0x02 -- Right mouse button
    local VK_MBUTTON  = 0x04 -- Middle mouse button
    local VK_XBUTTON1 = 0x05 -- X1 mouse button (Back)
    local VK_XBUTTON2 = 0x06 -- X2 mouse button (Forward)
    
    sleep(1000)
    print"Waiting for Left Mouse Button pressed"
    repeat
       sleep()
    until is_key_down(VK_LBUTTON)
    print"Left Mouse Button is down now"
    

    If you want to handle WM_LBUTTONDOWN message that would be a more complex solution.