保持电脑不息屏-skill
1.创建项目文件C#
NoSleepApp.csproj:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /><PropertyGroup><Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration><Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform><ProjectGuid>{12345678-1234-1234-1234-123456789012}</ProjectGuid><OutputType>Exe</OutputType><RootNamespace>NoSleepApp</RootNamespace><AssemblyName>NoSleepApp</AssemblyName><TargetFrameworkVersion>v4.5</TargetFrameworkVersion><FileAlignment>512</FileAlignment><AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects><Deterministic>true</Deterministic></PropertyGroup><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "><PlatformTarget>AnyCPU</PlatformTarget><DebugSymbols>true</DebugSymbols><DebugType>full</DebugType><Optimize>false</Optimize><OutputPath>bin\Debug\</OutputPath><DefineConstants>DEBUG;TRACE</DefineConstants><ErrorReport>prompt</ErrorReport><WarningLevel>4</WarningLevel></PropertyGroup><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "><PlatformTarget>AnyCPU</PlatformTarget><DebugType>pdbonly</DebugType><Optimize>true</Optimize><OutputPath>bin\Release\</OutputPath><DefineConstants>TRACE</DefineConstants><ErrorReport>prompt</ErrorReport><WarningLevel>4</WarningLevel></PropertyGroup><ItemGroup><Reference Include="System" /><Reference Include="System.Configuration" /><Reference Include="System.Core" /><Reference Include="System.Drawing" /><Reference Include="System.Windows.Forms" /><Reference Include="System.Xml.Linq" /><Reference Include="System.Data.DataSetExtensions" /><Reference Include="Microsoft.CSharp" /><Reference Include="System.Data" /><Reference Include="System.Net.Http" /><Reference Include="System.Xml" /></ItemGroup><ItemGroup><Compile Include="Program.cs" /><None Include="App.config" /></ItemGroup><Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
2.创建主文件程序
Program.cs
using System;
using System.Configuration;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;namespace NoSleepApp
{class Program{// 导入Windows API防止系统休眠[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);[Flags]public enum EXECUTION_STATE : uint{ES_AWAYMODE_REQUIRED = 0x00000040,ES_CONTINUOUS = 0x80000000,ES_DISPLAY_REQUIRED = 0x00000002,ES_SYSTEM_REQUIRED = 0x00000001}private static Timer _timer;private static bool _isRunning = true;static void Main(string[] args){Console.WriteLine("防熄屏程序 v1.0");Console.WriteLine("====================");// 读取配置int delayTimer = GetConfigValue("delayTimer", 10);int movePixels = GetConfigValue("movePixels", 10);Console.WriteLine($"配置参数:");Console.WriteLine($" - 移动间隔: {delayTimer} 秒");Console.WriteLine($" - 移动像素: {movePixels} 像素");Console.WriteLine();Console.WriteLine("程序运行中...");Console.WriteLine("按 'q' 键退出程序");Console.WriteLine("====================");// 设置控制台Ctrl+C事件处理Console.CancelKeyPress += (sender, e) =>{e.Cancel = true;StopProgram();};// 防止系统休眠SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED);try{// 创建定时器移动鼠标_timer = new Timer(state =>{MoveMouseSlightly(movePixels);Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - 已执行防熄屏操作");}, null, 0, delayTimer * 1000);// 监听按键退出while (_isRunning){if (Console.KeyAvailable){var key = Console.ReadKey(true);if (key.KeyChar == 'q' || key.KeyChar == 'Q'){StopProgram();}}Thread.Sleep(100);}}catch (Exception ex){Console.WriteLine($"程序出错: {ex.Message}");}finally{Cleanup();}}static void StopProgram(){_isRunning = false;Console.WriteLine("正在停止程序...");}static void Cleanup(){// 停止定时器_timer?.Dispose();// 恢复系统休眠设置SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);Console.WriteLine("程序已退出,系统休眠设置已恢复");Console.WriteLine("按任意键关闭窗口...");Console.ReadKey();}static int GetConfigValue(string key, int defaultValue){try{string value = ConfigurationManager.AppSettings[key];if (int.TryParse(value, out int result)){// 验证范围if (key == "delayTimer"){if (result >= 1 && result <= 60)return result;elseConsole.WriteLine($"警告: delayTimer值{result}超出范围(1-60),使用默认值{defaultValue}");}else if (key == "movePixels"){if (result >= 1 && result <= 100)return result;elseConsole.WriteLine($"警告: movePixels值{result}超出范围(1-100),使用默认值{defaultValue}");}}else{Console.WriteLine($"警告: 无法读取{key}配置,使用默认值{defaultValue}");}return defaultValue;}catch (Exception ex){Console.WriteLine($"读取配置{key}时出错:{ex.Message},使用默认值{defaultValue}");return defaultValue;}}static void MoveMouseSlightly(int pixels){try{Point currentPos = Cursor.Position;// 向右下移动Cursor.Position = new Point(currentPos.X + pixels, currentPos.Y + pixels);// 短暂延迟后移回原位置Thread.Sleep(50);Cursor.Position = currentPos;}catch (Exception ex){Console.WriteLine($"移动鼠标时出错: {ex.Message}");}}}
}
3.创建配置文件:JunGe.config
<?xml version="1.0" encoding="utf-8">
<configuration><startup><supportRuntime version="4.0" sku=".NETFramework,Version=v4.5"/></startup><appSettings><!--The amount of time to wait before moving the mouse pointer each time,Min=1,Max=60,Default=10,Unite=Second.--><add Key="delayTimer" value="1"/><!--Pixels per mouse pointer movement,Min=1,Max=100,Default=10.--><add Key="movePixels" value="3"/></appSettings>
</configuration>
4.编译生成exe步骤程序
方法1:【使用Visual Studio】
a.创建新的控制台应用程序
b.将上述文件内容复制到对应文件中
c.在解决方案资源管理器中右键项目→生成
d.在bin\Debug或bin\Release文件夹中找到NoSleepApp.exe