For this you need IOKit. The code will include writing kext and capturing keyboard events and choosing whether to pass them to user space. Writing the whole approach here would be too complicated and big, but I can offer a few links.
KeyRemap4MacBook code has a fairly low low-level code to read and intercept the device.
Here is the user kext that the author wrote: https://github.com/tekezo/KeyRemap4MacBook/tree/master/src/core/kext
I suggest you familiarize yourself with the code to find out how it intercepted the keys, reassigned them according to the user configuration, and sent them to the user space.
source share