Wiggling the mouse - c#

OK. This is a bit of a vanity app, but I had a situation today at work where I was in a training class and the machine was set to lock every 10 minutes. Well, if the trainers got excited about talking - as opposed to changing slides - the machine would lock up.
I'd like to write a teeny app that has nothing but a taskbar icon that does nothing but move the mouse by 1 pixel every 4 minutes.
I can do that in 3 ways with Delphi (my strong language) but I'm moving to C# for work and I'd like to know the path of least resistance there.

for C# 3.5
without notifyicon therefore you will need to terminate this application in task manager manually
using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };
timer.Start();
Application.Run();
}
}

The "correct" way to do this is to respond to the WM_SYSCOMMAND message. In C# this looks something like this:
protected override void WndProc(ref Message m)
{
// Abort screensaver and monitor power-down
const int WM_SYSCOMMAND = 0x0112;
const int SC_MONITOR_POWER = 0xF170;
const int SC_SCREENSAVE = 0xF140;
int WParam = (m.WParam.ToInt32() & 0xFFF0);
if (m.Msg == WM_SYSCOMMAND &&
(WParam == SC_MONITOR_POWER || WParam == SC_SCREENSAVE)) return;
base.WndProc(ref m);
}
According to MSDN, if the screensaver password is enabled by policy on Vista or above, this won't work. Presumably programmatically moving the mouse is also ignored, though I have not tested this.

When I work from home, I do this by tying the mouse cord to a desktop fan which oscillates left to right. It keeps the mouse moving and keeps the workstation from going to sleep.

Something like this should work (though, you will want to change the interval).
public Form1()
{
InitializeComponent();
Timer Every4Minutes = new Timer();
Every4Minutes.Interval = 10;
Every4Minutes.Tick += new EventHandler(MoveNow);
Every4Minutes.Start();
}
void MoveNow(object sender, EventArgs e)
{
Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y - 1);
}

(Windows 10 / .Net 5 / C# 9.0)
Instead of faking activity, you could
inform the system that it is in use, thereby preventing the system
from entering sleep or turning off the display while the application
is running
using SetThreadExecutionState, as described on PInvoke.net :
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace VanityApp
{
internal static class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern ExecutionState SetThreadExecutionState(ExecutionState esFlags);
[Flags]
private enum ExecutionState : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
}
private static void Main()
{
using AutoResetEvent autoResetEvent = new AutoResetEvent(false);
using Timer timer = new Timer(state => SetThreadExecutionState(ExecutionState.ES_AWAYMODE_REQUIRED | ExecutionState.ES_CONTINUOUS | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_SYSTEM_REQUIRED), autoResetEvent, 0, -1);
autoResetEvent.WaitOne();
}
}
}
The Timer is a System.Threading.Timer, with its handy constructor, and it uses AutoResetEvent.WaitOne() to avoid exiting immediately.

Raf provided a graceful answer to the problem for Win10 world, but unfortunately, his autoResetEvent.WaitOne() instruction blocks the thread, and therefore it must be in a separate thread of its own.
What worked for me can actually run in the main thread, the code doesn't have to be placed in the Main() method, and you can actually have a button to enable this functionality and one to disable it.
First, you certainly need to define the execution state flags:
[Flags]
private enum ExecutionState : uint // options to control monitor behavior
{
ES_AWAYMODE_REQUIRED = 0x00000040, // prevent idle-to-sleep
ES_CONTINUOUS = 0x80000000, // allow monitor power down
ES_DISPLAY_REQUIRED = 0x00000002, // prevent monitor power down
ES_SYSTEM_REQUIRED = 0x00000001 // keep system awake
}
Now, whenever you want to keep your system awake and block your monitor from turning off or idling to sleep, all you need to do, is execute a single command:
SetThreadExecutionState(ExecutionState.ES_AWAYMODE_REQUIRED | ExecutionState.ES_CONTINUOUS | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_SYSTEM_REQUIRED);
Then, if you want to undo this action and return your system back to its original execution state, just issue the following command:
SetThreadExecutionState(ExecutionState.ES_CONTINUOUS);
Keep in mind, each command will return the previous execution state, which means, when you first alter this state, you can cache the returned value locally and use it if/when you want to restore the previous state.

Related

How to distinguish a physical mouse click from a code one?

I'm writing an autoclicker right now. I have a very difficult problem to solve at my level of knowledge.
I have low level hooks to detect Mouse KeyDown & KeyUp.
private bool LeftButtonStatus;
private void AutoClicker_Load(object sender, EventArgs e)
{
core.mouseHook.LeftButtonDown += new MouseHook.MouseHookCallback(mouseHook_LeftKeyDown);
core.mouseHook.LeftButtonUp += new MouseHook.MouseHookCallback(mouseHook_LeftKeyUp);
}
private void mouseHook_LeftKeyDown(MouseHook.MSLLHOOKSTRUCT ma)
{
LeftButtonStatus = true;
StartClicking();
}
private void mouseHook_LeftKeyUp(KeyboardHook.VKeys key)
{
LeftButtonStatus = false;
StartClicking();
}
private void StartClicking()
{
if (LeftButtonStatus)
LeftButtonTimer.Start();
else
LeftButtonTimer.Stop();
}
private void LeftButtonTimer_Tick(object sender, EventArgs e)
{
Core.LeftClick();
}
My click method in the Core class looks like this:
[DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
public static void LeftClick()
{
mouse_event(((int)KeyStates.LeftDown) | ((int)KeyStates.LeftDown), 0, 0, 0, 0);
}
The problem is that when I call Core.LeftClick(); my hooks detect it
and stops the Timer.
How to do I make sure Core.LeftClick(); is ignored by the mouseHook_LeftKeyUp and mouseHook_LeftKeyDown methods?
You could use a flag in your own code where you set ignore = true in LeftClick() and check if (ignore == true) in your hook methods. But the problem there is you open yourself up to a race condition where a user-generated click could be processed between the time that it's set to true and when your hook is run, which would lead to a user-generated click being ignored.
A better way would be to use the dwExtraInfo parameter of mouse_event. The documentation describes it as:
An additional value associated with the mouse event.
This seems like a great way to send some flag along in the event itself.
It is meant to be a pointer to a location in memory for some data, but I found an example of someone setting it to some arbitrary integer value (in their case 111) and it presumably worked. You could try that.
It would look something like this:
public static void LeftClick()
{
mouse_event(((int)KeyStates.LeftDown) | ((int)KeyStates.LeftDown), 0, 0, 0, 111);
}
private void mouseHook_LeftKeyDown(MouseHook.MSLLHOOKSTRUCT ma)
{
if (ma.dwExtraInfo == 111) return;
LeftButtonStatus = true;
StartClicking();
}
Your method signature for mouseHook_LeftKeyUp is different, but is that correct? If you can change that to use MSLLHOOKSTRUCT too, then you can do the same there, if you need to.
In your DllImport attribute, the type of dwExtraInfo should technically be IntPtr, but in this case it shouldn't matter.
This answer consolidates and incorporates info and ideas from other SO posts here and here.
Your question is how to distinguish a physical mouse click from a virtual one. I see that in your code you're using a mouse hook and one way to "close the loop" is by examining the dwExtraInfo flag in the callback per Gabriel Luci's excellent suggestion. But what I set out to do is find a threadsafe approach that doesn't rely on a hook to detect auto clicks so I ended up discarding the mouse hook for my testing. And I tried several things, but what I found was most reliable in my experience is to essentially set a ~100 ms watchdog timer using a thread synchronization object (like the easy-to-use SemaphoreSlim). This semaphore can be tested by whatever target ultimately consumes the click to determine whether the WDT is has expired by calling Wait(0) on the semaphore and looking at the bool return value.
In the first of two tests, I checked the AutoClick button and let it run. As expected, the physical click shows up in black and the auto clicks show up in blue. The indicators all light up as expected.
For the autoClick methods, I used SendInput since mouse_event is obsolete (see Hans Passant comment on this post.
public void autoClick(Control control)
{
autoClick(new Point
{
X = control.Location.X + control.Width / 2,
Y = control.Location.Y + control.Height / 2,
});
}
public void autoClick(Point clientPoint)
{
Cursor.Position = PointToScreen(clientPoint);
var inputMouseDown = new INPUT { Type = Win32Consts.INPUT_MOUSE };
inputMouseDown.Data.Mouse.Flags = (uint)MOUSEEVENTF.LEFTDOWN;
// Go ahead and decorate with a flag as Gabriel Luci suggests.
inputMouseDown.Data.Mouse.ExtraInfo = (IntPtr)MOUSEEXTRA.AutoClick;
var inputMouseUp = new INPUT { Type = Win32Consts.INPUT_MOUSE };
inputMouseUp.Data.Mouse.Flags = (uint)MOUSEEVENTF.LEFTUP;
var inputs = new INPUT[]
{
inputMouseDown,
inputMouseUp,
};
if (0 == SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT))))
{
Debug.Assert(false, "Error: SendInput has failed.");
}
}
[Flags]
enum MOUSEEXTRA : uint{ AutoClick = 0x40000000, }
The handler for the Auto Click 5 checkbox positions and clicks the mouse to light up 5 "indicator" check boxes.
const int SETTLE = 100;
SemaphoreSlim _sslimAutoClick = new SemaphoreSlim(1, 1);
/// <summary>
/// Responds to the button by auto-clicking 5 times.
/// </summary>
private async void onAutoClick(object sender, EventArgs e)
{
if (checkBoxAutoClick.Checked)
{
checkBoxAutoClick.Enabled = false;
foreach (var indicator in indicators)
{
await _sslimAutoClick.WaitAsync();
autoClick(indicator);
// Don't await here. It's for the benefit of clients.
Task
.Delay(SETTLE)
.GetAwaiter()
.OnCompleted(() =>_sslimAutoClick.Release());
// Interval between auto clicks.
await Task.Delay(TimeSpan.FromSeconds(2));
}
checkBoxAutoClick.Enabled = true;
checkBoxAutoClick.Checked = false;
}
}
As a more rigorous test, I repeated this but while the 5x autoclick is running I did a few manual clicks to make sure they intersperse and print in black. Again, it worked as expected.
If you'd like to browse the full code or experiment with it, the full sample code is on GitHub.

Netduino InterruptPort Inconsistency

Im writing a Netduino 3 program that will control turn lights and other relays for hayrides. My program was written before I got the device, so Im not sure how well it will work, but Im already having a problem with one of the buttons (hazardButton). When applying 3.3v it doesn't cause the interrupt to trigger. Applying 5v does the same, however when applying GND it triggers the interrupt, but when re-applying GND it doesn't turn off the interrupt.
Here's my code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace Tractor_Mate
{
public class Program
{
static InterruptPort hazardButton = new InterruptPort(Pins.GPIO_PIN_D0, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
static OutputPort hazardLights = new OutputPort(Pins.ONBOARD_LED, false);
static bool hazardsActive = false;
public static void Main()
{
Debug.Print("Initializing Inputs... ");
hazardButton.OnInterrupt += new NativeEventHandler(hazardButton_OnInterrupt);
Thread.Sleep(Timeout.Infinite);
}
static void hazardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
while (data2 == 0)
{
hazardLights.Write(true);
Thread.Sleep(500);
hazardLights.Write(false);
Thread.Sleep(500);
hazardsActive = true;
}
hazardsActive = false;
}
}
}
Im getting the problem with the Hazard Lights and haven't tried any of the others yet. Im wiring the buttons up so that when the pin goes HIGH it will trigger, and then when LOW it turns it off.
public class Program
{
static InterruptPort hazardButton = new InterruptPort(Pins.GPIO_PIN_D0, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
static OutputPort hazardLights = new OutputPort(Pins.ONBOARD_LED, false);
static volatile bool hazardsActive = false;
public static void Main()
{
Debug.Print("Initializing Inputs... ");
hazardButton.OnInterrupt += new NativeEventHandler(hazardButton_OnInterrupt);
bool lightOn = true;
while (true)
{
if (!hazardsActive)
{
hazardLights.Write(false);
}
else
{
hazardLights.Write(lightOn);
lightOn = !lightOn;
}
Thread.Sleep(500);
}
}
static void hazardButton_OnInterrupt(uint data1, uint data2, DateTime time)
{
hazardsActive = !hazardsActive;
}
}
I'm unable to test this since I don't have the Netduino SDK installed (I have a NetDuino, but its been a while since I played with it). The principle is pretty easy:
The interrupt only toggles the hazards being on or off. The variable is marked volatile because it can be set from multiple threads and it needs to be read from the register not a thread cache, so volatile tells the compiler not to optimize it.
The main method has an infinite loop that examines if the hazards are on or off. When the hazards are off (first part of the if), it writes false to the output pin (presumably turning the lights off, unless the pin is inverted).
When the hazards are on (else part), it writes a value to the pin then inverts the value so the next time it turns it off, then on, then off, etc. The last part of the loop just waits 500ms before looping again.
Note
Depending on the "quality" of the contacts in the button you are using, you may need to add debouncing logic to the interrupt handler. "Bouncing" is a phenomenon with switch contacts (or any other mechanical contact) that can cause the contact to open/close many times very quickly when changing state. This is due to the electrical signal bridging the gap as the contacts are very close to each other (think static electricity jumping a gap). A lot of times this is handled on the hardware side by a capacitor, but I'm not sure for the Netduino how it handles it.

Prevent Windows workstation (desktop) from locking while running a WPF program

Issue:
I have a WPF fullscreen application, which acts as a dashboard. The computer is in domain and domain policies enforce the computer to be locked in 10 minutes after the last user activity. I want to prevent the workstation (or desktop) from locking automatically.
An example of such behavior: Windows Media Player, which prevents this while a movie is running.
Known solutions (kinda workarounds):
It is possible to send a Win32 Mouse Move event every fixed interval of time (for example, every minute)
It is possible to send a key to the program (for example "Left Shift" key up) every fixed interval of time (for example, every minute)
QUESTION:
How can I prevent windows workstation from locking without using these workarounds?
Disclaimer:
I was pretty sure, there should be a similar question answered somewhere on StackOverflow, but i didn't find any. I would appreciate, if you could point me into the right direction.
The solution has been pointed out through the comments, but I'm providing a simple starter solution for anyone else arriving via a web search:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
public App()
{
InitializeComponent();
App.Current.Startup += new StartupEventHandler((sender, e) =>
{
SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
});
App.Current.Exit += new ExitEventHandler((sender, e) =>
{
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
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004
}
An alternative place to put the logic would be within an event handler for StateChanged on your main application window:
this.StateChanged += new EventHandler((sender, e) =>
{
if (WindowState == System.Windows.WindowState.Maximized)
{
SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
}
else
{
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}
});

WPF: application Idle Time

I need to count the idle time of my WPF application (Idle time = when no keyboard input,mouse input (movement + clicks ) had occurred ).
So far I tried 2 approaches but none of them seem to be working:
Using the dispatcher to invoke a delegate each time it get a contextIdle priority, the problem is that binding and many other operations invoke it and thus I can't really use that.
using the input manager I registered to the "System.Windows.Input.InputManager.Current.PostProcessInput" event and each time it was invoked I restarted the idle time count.
The second approach seemed promising but the problem is that when the mouse is over the application (it has focus) I keep getting the event.
Any Other ideas? or maybe a way to modify the 2nd solution to work?
I solved the problem using a few different techniques rolled up to give me a pretty good solution. I use GetLastInput to work out when the system was last touched This is well documented elsewhere, but here's my method:
public static class User32Interop
{
public static TimeSpan GetLastInput()
{
var plii = new LASTINPUTINFO();
plii.cbSize = (uint)Marshal.SizeOf(plii);
if (GetLastInputInfo(ref plii))
return TimeSpan.FromMilliseconds(Environment.TickCount - plii.dwTime);
else
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO {
public uint cbSize;
public uint dwTime;
}
}
This only tells me when the system has been idle, not the application. If the user clicks into Word and works there for an hour, I still want a timeout. To handle this case, I simply remember when my application loses focus by overriding the OnDeactivated and OnActivated methods on the application object:
override protected void OnDeactivated(EventArgs e)
{
this._lostFocusTime = DateTime.Now;
base.OnDeactivated(e);
}
protected override void OnActivated(EventArgs e)
{
this._lostFocusTime = null;
base.OnActivated(e);
}
My IsIdle routine was added to the application object. It handles the global case where the app has focus but nothing happened (IsMachineIdle) and the specific case where the application lost focus while the user is doing other stuff (isAppIdle ):
public bool IsIdle
{
get
{
TimeSpan activityThreshold = TimeSpan.FromMinutes(1);
TimeSpan machineIdle = Support.User32Interop.GetLastInput();
TimeSpan? appIdle = this._lostFocusTime == null ? null : (TimeSpan?)DateTime.Now.Subtract(_lostFocusTime.Value);
bool isMachineIdle = machineIdle > activityThreshold ;
bool isAppIdle = appIdle != null && appIdle > activityThreshold ;
return isMachineIdle || isAppIdle;
}
}
The last thing I did was create a timer loop that polled this flag event few seconds.
This seems to work fine.
Well no one seemed to answer so I continued digging and found a relatively simple solution using the OS last input + up time. the code is really simple but this solution make me do data polling which I never recommend and also instead of being in the application level it's in the OS level which is not the exact solution I needed.
If someone ever opens this thread this is the code, just use GetIdleTime():
public class IdleTimeService
{
//Importing the Dll & declaring the necessary function
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
/// <summary>
/// return the current idle time (in ms)
/// </summary>
/// <returns>current idle time in ms</returns>
public static int GetIdleTime()
{
//Creating the object of the structure
LASTINPUTINFO lastone = new LASTINPUTINFO();
//Initialising
lastone.cbSize = (uint)Marshal.SizeOf(lastone);
lastone.dwTime = 0;
int idleTime = 0;
//To get the total time after starting the system.
int tickCount = System.Environment.TickCount;
//Calling the dll function and getting the last input time.
if (GetLastInputInfo(ref lastone))
{
idleTime = tickCount - (int)lastone.dwTime;
return idleTime;
}
else
return 0;
}
}

Keep a Windows Mobile Console App Running

I have a windows mobile app that look like this:
class Program
{
static void Main(string[] args)
{
RunHook runHook = new RunHook();
}
}
class RunHook
{
private HookKeys hook;
public RunHook()
{
hook = new HookKeys();
hook.HookEvent += EventForHook;
}
private void EventForHook(HookEventArgs e, KeyBoardInfo keyBoardInfo,
ref Boolean handled)
{
if ((keyBoardInfo.scanCode == 4) && (keyBoardInfo.vkCode == 114))
handled = true;
}
}
It will create a hook into the keyboard (I know that is frowned on by some). My issue is that I need the Main method to never return. This is going to run on devices owned by my company and we are using this to disable the phone hardware keys.
This seems like it should be simple, but I am stuck on it.
On normal .NET I would just call Console.Readline(), but that does not work on Windows Mobile Compact Framework. I have also tried Thread.Sleep(0), but it does not work either.
Thanks for any feedback.
Thread.Sleep(0) sleeps for zero milliseconds.
You probably want Thread.Sleep(Timeout.Infinite).
You might also consider creating an EventWaitHandle:
class Program
{
static public ManualResetEvent StopMain;
static void Main(string[] args)
{
StopMain = new ManualResetEvent(false);
RunHook runHook = new RunHook();
StopMain.WaitOne(); // waits until signalled
}
}
Then, if you were ever ready to exit Main(), you could call (from another thread):
Program.StopMain.Set();
If it going to run on devices that are owned by your company then why not run a small windows program in background. I mean just hide the window. Let it sit in your task bar.
Click on this link for more information on use of notification icon in CF.
not sure this will help but with native code youd call
LRESULT CallNextHookEx(
HHOOK hhk,
int nCode,
WPARAM wParam,
LPARAM lParam
);
in your handler to execute the default handling behaviour, havent tested this but i think if you dont call the next handler in the chain, nothing will happen
more info:
http://msdn.microsoft.com/en-us/library/ms644974%28VS.85%29.aspx
.
the link contains some managed code samples which may help
hth

Categories