Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Keyboard intercept input

I currently am able capture keyboard inputs while the program is not in focus using this solution.

Using global keyboard hook (WH_KEYBOARD_LL) in WPF / C#

I however want to know whether it is possible to stop other applications from using the input if it matches certain criteria, I would like to use it to capture bar-codes into my program while it runs in the background, but if you are working in notepad, the bar-code should preferably not be typed there as well.

I've added the following but the characters are still added to notepad as well.

if (nCode >= 0)
{
   if (wParam == (IntPtr)InterceptKeys.WM_KEYDOWN)
   {
      int vkCode = Marshal.ReadInt32(lParam);
      RawKeyEventArgs rk = new RawKeyEventArgs(vkCode, false);                    

      if (KeyDown != null)
         KeyDown(this, rk);
      if (rk.isHandled)
      {
         return (IntPtr)0;
      }
   }
}

return InterceptKeys.CallNextHookEx(hookId, nCode, wParam, lParam);

Is the return supposed to be something different?

like image 856
JacoT Avatar asked Oct 19 '22 03:10

JacoT


1 Answers

EDIT - I was looking at the wrong message it seems so I remove the entirety of the old answer.

This seems to be correct callback function LowLevelKeyboardProc callback function. This is what it says for the return value:

If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.

If nCode is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_KEYBOARD_LL hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.

So returning anything but zero should work.

like image 176
R.Rusev Avatar answered Nov 16 '22 14:11

R.Rusev