Skip to content

Instantly share code, notes, and snippets.

@pgaskin
Last active March 22, 2023 01:05
Show Gist options
  • Save pgaskin/9d3c601bc766a58ae0ee214f22190ab5 to your computer and use it in GitHub Desktop.
Save pgaskin/9d3c601bc766a58ae0ee214f22190ab5 to your computer and use it in GitHub Desktop.
<# ::
@@ start "" powershell -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -Command "Invoke-Expression (Get-Content -Raw '%~f0')"
#>
$ErrorActionPreference = "Stop"
try {
Add-Type -Language CSharp -ReferencedAssemblies $("System.Windows.Forms", "System.Drawing") @"
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class StayAwake : ApplicationContext {
[FlagsAttribute]
enum EXECUTION_STATE : uint {
ES_AWAYMODE_REQUIRED = 0x00000040, // replace sleep (incl manual) with a fake-sleep where cpu is still active (doesn't affect display/idle timer)
ES_CONTINUOUS = 0x80000000, // continuously set
ES_DISPLAY_REQUIRED = 0x00000002, // display timer
ES_SYSTEM_REQUIRED = 0x00000001, // idle timer
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
private NotifyIcon icon;
private EXECUTION_STATE state = EXECUTION_STATE.ES_CONTINUOUS;
StayAwake() {
icon = new NotifyIcon() {
Icon = Icon.ExtractAssociatedIcon("C:\\Windows\\System32\\msra.exe"),
//Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath), // use /win32icon:whatever.ico when compiling
ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Disable &idle timer", Toggle(EXECUTION_STATE.ES_SYSTEM_REQUIRED)),
new MenuItem("Keep &display on", Toggle(EXECUTION_STATE.ES_DISPLAY_REQUIRED)),
new MenuItem("Replace &sleep", Toggle(EXECUTION_STATE.ES_AWAYMODE_REQUIRED)),
new MenuItem("-"),
new MenuItem("E&xit", Exit),
}),
Visible = true,
};
icon.MouseClick += (object sender, MouseEventArgs e) => {
if (e.Button == MouseButtons.Left) {
typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(icon, null);
}
};
}
EventHandler Toggle(EXECUTION_STATE flag) {
return (object sender, EventArgs e) => {
SetThreadExecutionState(state ^= flag);
((MenuItem) sender).Checked = state.HasFlag(flag);
icon.Text = (state &~ EXECUTION_STATE.ES_CONTINUOUS).ToString();
};
}
void Exit(object sender, EventArgs e) {
icon.Visible = false;
Application.Exit();
}
public static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new StayAwake());
}
}
"@
[StayAwake]::Main()
} catch {
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show($Error, "Error")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment