Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/7896f0815f8d8590da4cbcf2d6fb50d2 to your computer and use it in GitHub Desktop.
Save smailliwcs/7896f0815f8d8590da4cbcf2d6fb50d2 to your computer and use it in GitHub Desktop.
NoSleep
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Distance" value="10" />
<add key="Timeout" value="1:00" />
</appSettings>
</configuration>
using System;
using System.Configuration;
namespace NoSleep
{
static class Configuration
{
public static int Distance
{
get
{
int distance;
bool valid = int.TryParse(ConfigurationManager.AppSettings["Distance"], out distance);
return valid ? distance : 10;
}
}
public static TimeSpan Timeout
{
get
{
TimeSpan timeout;
bool valid = TimeSpan.TryParseExact(ConfigurationManager.AppSettings["Timeout"], @"m\:s", null, out timeout);
return valid ? timeout : TimeSpan.FromMinutes(1.0);
}
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NoSleep
{
class Program
{
static void Main(string[] args)
{
EventWaitHandle done = new ManualResetEvent(false);
Task.Factory.StartNew(WaitForKeyPress).ContinueWith(task => done.Set());
JiggleMouse(done);
}
private static void WaitForKeyPress()
{
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
private static void JiggleMouse(EventWaitHandle done)
{
bool moveRight = true;
while (!done.WaitOne(Configuration.Timeout))
{
int dx = (moveRight ? 1 : -1) * Configuration.Distance;
User32.MoveMouse(dx, 0);
moveRight = !moveRight;
}
}
}
}
using System;
using System.Runtime.InteropServices;
namespace NoSleep
{
static class User32
{
public const uint INPUT_MOUSE = 0;
public const uint MOUSEEVENTF_MOVE = 0x0001;
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
public uint type;
public MOUSEINPUT mi;
}
[DllImport("user32.dll")]
public static extern IntPtr GetMessageExtraInfo();
[DllImport("user32.dll")]
public static extern uint SendInput(uint cInputs, INPUT[] pInputs, int cbSize);
public static void MoveMouse(int dx, int dy)
{
INPUT[] pInputs = new INPUT[]
{
new INPUT
{
type = INPUT_MOUSE,
mi = new MOUSEINPUT
{
dx = dx,
dy = dy,
mouseData = 0,
dwFlags = MOUSEEVENTF_MOVE,
time = 0,
dwExtraInfo = GetMessageExtraInfo()
}
}
};
SendInput(1, pInputs, Marshal.SizeOf(typeof(INPUT)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment