DeftSharp.Windows.Input

An open-source .NET library designed for keyboard and mouse control in Windows.

MIT License

Stars
53
Committers
11

Bot releases are hidden (Show)

DeftSharp.Windows.Input - Release 0.9 Latest Release

Published by Empiree 6 months ago

0.9 Release available!

What's new:

  • Added new functionality.
  • Changed the names of existing methods and added new overloads to them.
  • General improvements to the library's operations.

[Breaking changes] ⚠️

We had to change a few things about using the library. The goal of our changes is to create a more user-friendly and intuitive design. We try to minimize these things so that you don't have to edit already created code. Thank you for your understanding!

  • The UnsubscribeAll() method has been replaced by an overload of the Unsubscribe() method.
  • The UnbindAll() method has been replaced by an overload of the Unbind() method.
  • The ResetIntervals() method has been replaced by an overload of the ResetInterval() method.
  • The ReleaseAll() method has been replaced by an overload of the Release() method.
  • Changed the name of the interval in Subscribe methods. Now it is just interval instead of intervalOfClick.
var keyboardListener = new KeyboardListener();

keyboardListener.Subscribe(Key.Space, () =>
{
  Trace.WriteLine("Space");
}, interval: TimeSpan.FromSeconds(1)); // Instead of intervalOfClick

Changelog

KeyboardListener

  • Added new overloads for Subscribe methods.
  • Added new overloads for Unsubscribe methods.
  • The UnsubscribeAll() method has been replaced by an overload of the Unsubscribe() method.

KeyboardManipulator

  • The ReleaseAll() method has been replaced by an overload of the Release() method.
  • The ResetIntervals() method has been replaced by an overload of the ResetInterval() method.
  • Added a Simulate() method that can be used to simulate keyboard events such as KeyDown and KeyUp.
var keyboard = new KeyboardManipulator();
            
keyboard.Simulate(Key.LeftShift, KeyboardInputEvent.KeyDown); // Press the left Shift button
            
// ...
            
keyboard.Simulate(Key.LeftShift, KeyboardInputEvent.KeyUp); // Release the button

KeyboardBinder

  • The UnbindAll() method has been replaced by an overload of the Unbind() method.

MouseListener

  • Added new overloads for Unsubscribe methods.
  • The UnsubscribeAll() method has been replaced by an overload of the Unsubscribe() method.
  • Added IsKeyPressed() method, which returns whether the button is pressed or not.
var mouseListener = new MouseListener();

var isLeftButtonPressed = mouseListener.IsKeyPressed(MouseButton.Left);

MouseManipulator

  • The Click() method now supports the middle mouse button.
  • The ReleaseAll() method has been replaced by an overload of the Release() method.
  • Changed the IsKeyLocked() method, it now accepts the same event type as the Prevent method.
var mouse = new MouseManipulator();
            
mouse.Prevent(PreventMouseEvent.Scroll);

var isScrollLocked = mouse.IsKeyLocked(PreventMouseEvent.Scroll); // true

NumpadListener

  • Added IsListening property, which returns whether there are active subscriptions or not.
  • Added optional parameters for subscriptions, such as trigger interval and press event type.
var keyboardListener = new KeyboardListener();
var numpadListener = new NumpadListener(keyboardListener);
            
numpadListener.Subscribe(number =>
{
    Trace.WriteLine(number);
}, 
   interval: TimeSpan.FromSeconds(1),
   keyboardEvent: KeyboardEvent.KeyUp);

Other changes

  • Improvement in the use of tracking the current state of the keys.
  • XML comments improvement.
DeftSharp.Windows.Input - Release 0.8.2

Published by Empiree 6 months ago

0.8.2 Release available!

What's new:

  • Small changes to the classes

[Breaking changes]

  • The Speed property has been changed to the GetSpeed() method
  • The Layout property has been changed to the GetLayout() method
  • The Type property has been changed to the GetKeyboardType() method

Changelog

NumpadListener

  • Changed Unsubscribe() method in NumpadListener, now this class unsubscribes only from subscriptions that were created by itself
DeftSharp.Windows.Input - Release 0.8.1

Published by Empiree 6 months ago

0.8.1 Release available! (HotFix)

What's new:

  • Fixed multithreading bug in WinUI application
  • Class name changes

[Breaking changes]

  • PreventMouseOption class name has been changed to PreventMouseEvent

Changelog

  • Fixed a bug with multithreading in WinUI applications, which caused the application to start freezing.
  • PreventMouseOption class name has been changed to PreventMouseEvent.
DeftSharp.Windows.Input - Release 0.8

Published by Empiree 6 months ago

0.8 Release available!

What's new:

  • Added new classes
  • Bug fixes
  • Improving the functionality of existing classes

[Breaking changes]

  • Coordinates class name has been changed to Point
  • NumpadButton class name has been changed to NumButton
  • GetPosition() method changed to Position property

Changelog

MouseListener

  • GetPosition method changed to Position property.

MouseManipulator

  • Added a SetMouseSpeed() method that allows you to change the mouse speed.
  • Added an additional optional parameter to the Prevent() method that accepts the Func<bool> predicate, in order to block pressing only under a certain condition.
var mouseManipulator = new MouseManipulator();

mouseManipulator.Prevent(PreventMouseOption.Scroll, () =>
{
   var currentTime = DateTime.Now;

   if (currentTime.Minute > 30)
         return true;
                
    return false;
});

MouseInfo

New class that contains information about the mouse and its current state.

  • Added Speed property that returns the current mouse speed.
var mouseInfo = new MouseInfo();
            
Trace.WriteLine(mouseInfo.Speed); // 10

// The speed can be changed through the MouseManipulator class.

KeyboardInfo

New class that contains information about the keyboard and its current state.

  • Added Layout property that returns the current keyboard layout.
  • Added Type property that returns the keyboard type.
var keyboardInfo = new KeyboardInfo();
            
Trace.WriteLine(keyboardInfo.Layout.DisplayName); // English (United States)
Trace.WriteLine(keyboardInfo.Type.Name); // IBM enhanced (101- or 102-key) keyboard

Other changes

  • Fixed a bug where the event handler was called before the input event itself.
  • Fixed a bug where the SubscribeAll() method subscribed to some events multiple times.
  • Added extension method for Key - ToUnicode() which returns the interpretation of the key as a unicode string.
  • Coordinates class name has been changed to Point.
  • NumpadButton class name has been changed to NumButton.
DeftSharp.Windows.Input - Release 0.7.1

Published by Empiree 7 months ago

0.7.1 Release available!

What's new:

  • Improving the functionality of existing classes

[Breaking changes]

  • KeyboardManipulator - The name of the PressCombination method has been changed to Press

Changelog

KeyboardManipulator

  • The PressCombination method has been changed to an overload of the Press method that accepts a collection of keys:
var keyboardManipulator = new KeyboardManipulator();
            
keyboardManipulator.Press(Key.LeftCtrl, Key.V);
            
// before
// keyboardManipulator.PressCombination(new[]{Key.LeftCtrl, Key.V});

KeyboardBinder

  • Added Swap method that swaps button bindings between each other:
 var keyboardBinder = new KeyboardBinder();
 
 keyboardBinder.Swap(Key.Q, Key.W);
            
// before
// keyboardBinder.Bind(Key.Q, Key.W);
// keyboardBinder.Bind(Key.W, Key.Q);
  • Added GetBoundKey method, which returns the current button bind. If the bind of the button has not been changed, it will return the same button:
var keyboardBinder = new KeyboardBinder();
            
keyboardBinder.Bind(Key.C, Key.V);

keyboardBinder.GetBoundKey(Key.C); // return V
keyboardBinder.GetBoundKey(Key.V); // return V
keyboardBinder.GetBoundKey(Key.E); // return E

Other changes

  • Added XML comments to existing classes
DeftSharp.Windows.Input - Release 0.7

Published by Empiree 7 months ago

0.7 Release available!

What's new:

  • Improving the functionality of existing classes

[Breaking changes]

  • KeyboardManipulator - The name of the PreventMany method has been changed to Prevent
  • KeyboardBinder - The name of the BindMany method has been changed to Bind
  • MouseManipulator - The ClickPrevented event has been changed to InputPrevented

Changelog

KeyboardListener

  • Added generic KeyboardEvent.All event for Subscribe methods, which will be triggered on both KeyDown and KeyUp methods
var keyboardListener = new KeyboardListener();

keyboardListener.Subscribe(Key.LWin, (key, eventType) =>
{

   if(eventType is KeyboardInputEvent.KeyDown)
       Trace.WriteLine($"{key} pressed");

   if(eventType is KeyboardInputEvent.KeyUp)
        Trace.WriteLine($"{key} released");

}, keyboardEvent: KeyboardEvent.All);

KeyboardManipulator

  • Added an additional optional parameter to the Prevent method that accepts the Func<bool> predicate, in order to block pressing only under a certain condition
var keyboardManipulator = new KeyboardManipulator();

keyboardManipulator.Prevent(Key.Escape, () =>
{
   var currentTime = DateTime.Now;

   if (currentTime.Minute > 30)
         return true;
                
    return false;
});
  • Added SetInterval method, which allows you to set the frequency of pressing the specified button
  • Added ResetInterval method, which allows you to reset the set interval of a certain button
var keyboardManipulator = new KeyboardManipulator();

keyboardManipulator.SetInterval(Key.Space, TimeSpan.FromSeconds(1));
            
// ...
            
keyboardManipulator.ResetInterval(Key.Space);

// or

keyboardManipulator.SetInterval(Key.Space, TimeSpan.Zero);
  • The name of the PreventMany method has been changed to Prevent

KeyboardBinder

  • The name of the BindMany method has been changed to Bind

MouseManipulator

  • The ClickPrevented event has been changed to InputPrevented
  • Added Scroll method that allows you to scroll the mouse wheel
var mouseManipulator = new MouseManipulator();
            
mouseManipulator.Scroll(150); // Scroll up
mouseManipulator.Scroll(-150); // Scroll down

Other changes

  • Added handy methods for classes like KeyboardManipulator that can take multiple values at once
  • Namespaces refactoring
DeftSharp.Windows.Input - Release 0.6

Published by Empiree 7 months ago

0.6 Release available!

What's new:

  • Custom interceptors
  • MouseListener class improvement
  • KeyboardListener class improvement

Changelog

Custom Interceptors

Version 0.6 introduced the ability to create your own interceptors. This means that if your use case is unique and requires its own implementation, you can create a new interceptor, similar to KeyboardListener or KeyboardManipulator!

Let's try to do it together!

Our goal: block the scroll mouse event, and output all mouse events to the console except Move, since that event will quickly spam the console.

First, let's create an interceptor to block mouse scroll events:

public class ScrollDisabler : MouseInterceptor
{
    protected override bool IsInputAllowed(MouseInputArgs args)
    {
        if (args.Event is MouseInputEvent.Scroll)
            return false; // disallow mouse scroll input
        
        return true; // all other input events can be processed
    }
}

To do this, we need to inherit from the MouseInterceptor class and implement the IsInputAllowed method, which is responsible for blocking events.

Next, let's create another interceptor to output all events to the console.

public class MouseLogger : MouseInterceptor
{
    // Always allow input because it's a logger
    protected override bool IsInputAllowed(MouseInputArgs args) => true;

    // If the input event was successfully processed
    protected override void OnInputSuccess(MouseInputArgs args)
    {
        if (args.Event is MouseInputEvent.Move) // Don't log a move event
            return;
        
        Trace.WriteLine($"Processed {args.Event}");
    }

    // If the input event has been blocked
    protected override void OnInputFailure(MouseInputArgs args, IEnumerable<InterceptorInfo> failedInterceptors)
    {
        var failureReason = failedInterceptors.ToNames();
        
        Trace.WriteLine($"Failed {args.Event} by: {failureReason}");
    }
}

In addition to the familiar IsInputAllowed method, we have overridden two more methods for input processing.

OnInputSuccess - called if the input was processed successfully and no interceptor blocked it.

OnInputFailure - called if the event was blocked by one or more interceptors. In it we will get the list of these interceptors.

[!NOTE]
The implementation of these 2 interceptors can be placed in one interceptor, but it is better to separate it. So that each is responsible for its own task.

All we have to do is to call the Hook method of these two classes to make the interceptors work:

var scrollDisabler = new ScrollDisabler();
var mouseLogger = new MouseLogger();
            
scrollDisabler.Hook();
mouseLogger.Hook();

Now let's run our project and test their work:

image

In the Debug console, we can see that the mouse button events have fired. And mouse wheel scrolling was blocked by ScrollDisabler class. If we need to disable this interceptor, it is enough to call the Unhook method.

It was a simple implementation of a custom interceptor. In your scenarios they can be much larger and with stronger logic.

To do the same thing but using already created interceptors, just do this:

var mouseListener = new MouseListener();
var mouseManipulator = new MouseManipulator();

mouseListener.SubscribeAll(mouseEvent =>
{
     if (mouseEvent is MouseInputEvent.Move)
         return;
                
     Trace.WriteLine($"Processed {mouseEvent}");
});
            
mouseManipulator.Prevent(PreventMouseOption.Scroll);

mouseManipulator.ClickPrevented += mouseEvent => 
     Trace.WriteLine($"Failed {mouseEvent} by: MouseManipulator");

KeyboardListener

  • Added IsKeyPressed method, which returns whether the button is pressed or not
  • Added useful properties such as IsCapsLockActive, IsNumLockActive, etc

MouseListener

  • Added SubscribeAll method that subscribes to all mouse input events
  • Added overloading for Subscribe methods, now you can get the input event. This is especially useful when using generic events like ButtonDown and ButtonUp
DeftSharp.Windows.Input - Release 0.5

Published by Empiree 7 months ago

0.5 Release available!

What's new:

  • New useful methods (SubscribeAll, PressCombination, etc.)
  • New subscription types for MouseListener
  • Small changes

[Breaking change] : LeftButtonDoubleClick has been removed due to unstable operation.

Changelog

KeyboardListener

  • Added SubscribeAll method, which subscribes to all possible buttons (about 200)

KeyboardManipulator

  • Added PressCombination method, which accepts IEnumerable<Key> and synchronously presses specified keyboard buttons
var keyboardManipulator = new KeyboardManipulator();
Key[] paste = { Key.LeftCtrl, Key.V };

keyboardManipulator.PressCombination(paste);

MouseListener

  • Added new subscription types: MiddleButtonDown, MiddleButtonUp, Scroll
  • Added new generic subscriptions types: ButtonDown and ButtonUp. Which are not bound to a specific button
  • Removed LeftButtonDoubleClick subscription due to unstable operation

MouseManipulator

  • Added new types of prevent: MiddleButton and Scroll
  • Added a new overload of the Click method, which now does not need coordinates. Clicking is based on the current location of the mouse

Other changes

  • It is no longer possible to specify Key.None as a key. If you try to do so, the user will get an exception
DeftSharp.Windows.Input - Release 0.4

Published by Empiree 7 months ago

0.4 Release available!

What's new:

KeyboardListener

  • Sequence subscriptions
  • Combination subscriptions
  • Small changes of use

Changelog

KeyboardListener

The KeyboardListener class now has the ability to subscribe to combinations of button presses, as well as their sequence.

New Methods:

  • SubscribeSequence - subscribe to a sequence of button presses.
Key[] sequence = { Key.Q, Key.W, Key.E };
keyboardListener.SubscribeSequence(sequence, () =>
{
   // This code will trigger after successive presses of 'Q W E' buttons
});
  • SubscribeCombination - subscribe to a combination of button presses.
Key[] combination = { Key.Q, Key.W, Key.E };
keyboardListener.SubscribeCombination(combination , () =>
{
   // This code will be triggered by pressing the 'Q W E' button combination
});

It is also possible to call these methods once, using the SubscribeSequenceOnce and SubscribeCombinationOnce methods.

[!NOTE]
The length of combinations/sequences should be between 2 and 10 buttons.

Other changes

  • Removed overloading method for Unsubscribe(IEnumerable<Key> keys) due to the addition of new subscription types, as such, this method could cause misconception of usage.
  • The name of the KeyboardSubscription class has been changed to KeySubscription
DeftSharp.Windows.Input - Release 0.3

Published by Empiree 7 months ago

0.3 Release available!

What's new:

  • Keyboard Binder - a class for rebinding buttons
  • Small improvements (new methods)
  • Fixed bugs

Changelog

KeyboardBinder

A class that allows you to change the bindings of the specified buttons.

Methods:

  • Bind - binds one button to another:
keyboardBinder.Bind(Key.A, Key.B); // when the 'A' button is pressed, the 'B' button will be pressed instead.
  • BindMany - binds multiple buttons to a single button:
Key[] keys = { Key.Q, Key.W, Key.E };
keyboardBinder.BindMany(keys, Key.B); // Q, W, E -> B
  • Unbind and UnbindAll - allow you to unbind the specified keys:
keyboardBinder.Bind(Key.Q, Key.W); 
keyboardBinder.Unbind(Key.Q);

// Or

keyboardBinder.UnbindAll();

Important! The principle of KeyboardBinder operation is the same as in the KeyboardManipulator class. You can have as many objects as you want, but they all work with one single interceptor. Therefore, the state is shared between all KeyboardBinder objects.

Other minor changes

  • Fixed a bug where MouseManipulator.Prevent(), when selecting any Up event, could completely block normal mouse operation.
  • Fixed a bug when KeyboardListener class object was lost but could not be destroyed by GC because of active subscriptions. Now after time expiration, such class will be unsubscribed and will be correctly processed by GC.
  • Now the Subscribe / SubscribeOnce methods return a Subscription object with subscription details.
  • The KeyReleased event has been deleted.
  • The KeyPrevented event has been redesigned. Now, KeyPrevented is triggered not when the Prevent() method is used, but when an attempt is made to click on a button that has been locked. This change allows more flexibility in handling input events.
  • Several handy methods have been added. For example, PreventMany() to the KeyboardManipulator class.
  • Added DangerousBehavior attribute. Which shows potentially dangerous methods.
DeftSharp.Windows.Input - Release 0.2

Published by Empiree 8 months ago

0.2 Release available!

What's new:

  • Mouse Manipulator - a mouse control class.
  • Keyboard Manipulator - a keyboard control class.
  • Fixed minor bugs

Changelog:

KeyboardManipulator - a keyboard control class is created to emulate pressing buttons, as well as disabling them.

Methods:

  • Press - emulates pressing any key on the keyboard.:
keyboardManipulator.Press(Key.A);
  • Prevent - prohibits pressing the specified button:
keyboardManipulator.Prevent(Key.A);
  • Release - releases the button from the user ban using the 'Prevent' method:
keyboardManipulator.Release(Key.A);

You can also use the ReleaseAll() method:

keyboardManipulator.ReleaseAll();

Important! Locked buttons are shared among all KeyboardManipulator classes. You don't have to worry that an object in this class has locked a particular button and you no longer have access to that object.

For example:

var first = new KeyboardManipulator();
first.Prevent(Key.A);
            
var second = new KeyboardManipulator();
second.Prevent(Key.B);
            
first.LockedKeys // Key.A, Key.B
second.LockedKeys // Key.A, Key.B

Also, several events are available: KeyPrevented and KeyReleased. They are only triggered by a successful operation. For example, if a button is locked several times, the KeyPrevented event will be triggered only once.

Mouse Manipulator - a mouse control class.

Methods:

  • Click - presses a specified button at specified coordinates.
mouseManipulator.Click(500, 500, MouseButton.Left); // the left mouse button will be pressed at the coordinates: x: 500, y:500
  • Prevent / Release - are made similar to the Keyboard Manipulator
DeftSharp.Windows.Input - Release 0.1

Published by Empiree 8 months ago

DeftSharp.Windows.Input Release 0.1

Features:

  • Keyboard subscriptions
  • Mouse subscriptions

Classes:

  • KeyboardListener
  • MouseListener
  • NumpadListener