C# Bejeweled 3 Bot — part 3— handling mouse and keyboard
Making mouse move and click on stuff in C# is probably the easiest thing I did in my life. Here is the class:
With this class, if you call Move(…) followed by a Click() you will have your mouse and raise click events on any point on the screen.
Just after testing the mouse behaviour I saw a major flaw in my design: when your program takes over the mouse control and clicks on things twice every 300 ms and on top of that because your program is not in focus anymore (you are doing some heavy work with your mouse on your web browser after all) you can’t really handle the typical key events on your form (and you accidentally start calling your friends on skype), which brings us to:
(Globally) handling keyboard events
Before you start thinking of me in a high manner, let’s give credit where it’s due. And it’s due to Stephen Toub for writing the article “Low-Level Keyboard Hook in C#”. Using his solution and a bit of hackery I started forwarding global key press events to my form, just like this:
To forward the key presses to my form it’s enough that I subscribe to the KeyIntercepted event, just like that:
In my Form_KeyDown(…) method I check if the pressed key was Escape and if it was then I stop the main timer so that I can move my mouse by myself.