Created
November 3, 2021 21:30
-
-
Save Eimaen/edb64ac7460be99c0ec5a27760a9704d to your computer and use it in GitHub Desktop.
Simple class that listens to mouse clicks and triggers an event.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MouseEventArgs : EventArgs | |
{ | |
public bool Release { get; private set; } | |
public short StateRaw { get; private set; } | |
public MouseEventArgs(bool release, short state) | |
{ | |
Release = release; | |
StateRaw = state; | |
} | |
} | |
class MouseListener : IDisposable | |
{ | |
[DllImport("user32.dll")] | |
static extern short GetKeyState(int vKey); | |
public delegate void MouseClick(object sender, MouseEventArgs args); | |
public event MouseClick OnMouseClick; | |
private Thread thread = null; | |
private short rawState = short.MinValue; | |
public MouseListener() => thread = new Thread(() => { while (true) Tick(); }); | |
public void Start() => thread.Start(); | |
private void Tick() | |
{ | |
short rawStateNow = GetKeyState(0x01); | |
bool state = rawStateNow < 0; | |
if (rawStateNow != rawState) | |
{ | |
OnMouseClick(this, new MouseEventArgs(!state, rawStateNow)); | |
rawState = rawStateNow; | |
} | |
} | |
public void Dispose() | |
{ | |
thread.Abort(); | |
thread = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment