Skip to content

Instantly share code, notes, and snippets.

@Eimaen
Created November 3, 2021 21:30
Show Gist options
  • Save Eimaen/edb64ac7460be99c0ec5a27760a9704d to your computer and use it in GitHub Desktop.
Save Eimaen/edb64ac7460be99c0ec5a27760a9704d to your computer and use it in GitHub Desktop.
Simple class that listens to mouse clicks and triggers an event.
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