MediatedCommunications / WindowsInput

Capture and Simulate Keyboard and Mouse Input
MIT License
115 stars 17 forks source link

Block input? #2

Closed CactusPie closed 4 years ago

CactusPie commented 4 years ago

Hi, thanks for sharing this library! I'm currently using it for implementing a mod for a game I'm playing, however I'm wondering if it's possible to block certain keys from being actually passed to any applications running on the system? For instance, if I press W it will be captured by my application, but not by the game.

Thanks in advance!

TonyValenti commented 4 years ago

Hi @CactusPie ! You can definitely do what you're wanting. Here's an example:

    public static class DisallowKeys {

        public static async Task Start() {
            Console.WriteLine("Disallowing the 'W' key on the keyboard for 10 seconds");

            var Keyboards = new List<IKeyboardEventSource>();
            for (int i = 0; i < 1; i++) {
                Keyboards.Add(Capture.Global.KeyboardAsync());
            }

            foreach (var item in Keyboards) {
                item.KeyEvent += Item_KeyEvent;
            }

            await Task.Delay(1000 * 10);

            foreach (var item in Keyboards) {
                item?.Dispose();
            }

        }

        private static void Item_KeyEvent(object sender, EventSourceEventArgs<KeyboardEvent> e) {
            if (e.Data.KeyDown?.Key == WindowsInput.Events.KeyCode.W || e.Data.KeyUp?.Key == WindowsInput.Events.KeyCode.W) {
                //Tell the OS to ignore this key
                e.Next_Hook_Enabled = false;
            }
        }

    }
CactusPie commented 4 years ago

Awesome! Thanks a lot