Move mouse cursor continuously
This wpf application will keep the mouse pointer moving and will not let the windows lock.
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Threading;
namespace MouseMover
{
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
[DllImport("kernel32.dll")]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
private DispatcherTimer timer;
private int x = 0;
private int y = 0;
private int dx = 1;
private int dy = 1;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Tick += Timer_Tick;
timer.Start();
// Disable system power-saving features
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED);
}
private void Timer_Tick(object sender, EventArgs e)
{
// Update mouse position
x += dx;
y += dy;
// Change direction if mouse hits the edge
if (x < 0 || x > SystemParameters.PrimaryScreenWidth)
{
dx = -dx;
}
if (y < 0 || y > SystemParameters.PrimaryScreenHeight)
{
dy = -dy;
}
// Set new mouse position
SetCursorPos(x, y);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Restore system power-saving features
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}
}
[FlagsAttribute]
public enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
}
}