Reputation: 13683
I'm making a simple application in C# , with Microsoft Visual Studio.
The application makes the cursor move to a point (out of form window) and clicks a number of times. I start the clicking loop by pressing X. So if you are interested the code looks like :
public void Wait(int milliseconds)
{
System.Threading.Thread.Sleep(milliseconds);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;
public void MouseClick(Point pos, int click = 0)
{
int x = pos.X;
int y = pos.Y;
//MessageBox.Show("clicking mouse on " + pos.ToString());
if (click == 1)
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
}
else
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
}
public void MouseMove(int x, int y)
{
MouseMove(new Point(x,y));
}
public void MouseMove(Point target)
{
Cursor.Position = target;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
MessageBox.Show(Cursor.Position.ToString());
}
MouseMove(42, 42);
if (e.KeyCode == Keys.X)
{
MessageBox.Show(Cursor.Position.ToString());
Wait(42);
Random r = new Random();
for (int i = 0; i < number_of_times ; i++)
{
Wait(r.Next(42));
MouseClick(Cursor.Position);
}
}
}
But, as you can see, once the clicking starts, the form goes back (not visible in the screen), so it cannot detect keypresses. So how can I stop the clicking loop ? If I do Ctrl + Alt + Del, it pauses, then I open the task manager but the clicking goes on.
Maybe a way to detect ctrl alt del? or any other keypress, when the window is down?
Thanks for any help !
Upvotes: 0
Views: 369
Reputation: 5525
Take a look at the following article: Low-Level Keyboard Hook in C#.
Also, here is a code example: https://gist.github.com/Ciantic/471698.
A global hotkey might be a good solution: http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/
Upvotes: 1