我正在开发一个C#应用程序,它在后台运行,没有任何Windows控件.
我想通知Windows我的应用程序仍处于活动状态,以防止Windows进入空闲状态.
是否有任何API可以从我的应用程序调用,通知Windows操作系统我的应用程序仍然存在?
提前致谢.
Joa*_*oao 41
您将使用SetThreadExecutionState函数.像这样的东西:
public partial class MyWinForm: Window
{
private uint fPreviousExecutionState;
public Window1()
{
InitializeComponent();
// Set new state to prevent system sleep
fPreviousExecutionState = NativeMethods.SetThreadExecutionState(
NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
if (fPreviousExecutionState == 0)
{
Console.WriteLine("SetThreadExecutionState failed. Do something here...");
Close();
}
}
protected override void OnClosed(System.EventArgs e)
{
base.OnClosed(e);
// Restore previous state
if (NativeMethods.SetThreadExecutionState(fPreviousExecutionState) == 0)
{
// No way to recover; already exiting
}
}
}
internal static class NativeMethods
{
// Import SetThreadExecutionState Win32 API and necessary flags
[DllImport("kernel32.dll")]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}
Run Code Online (Sandbox Code Playgroud)
Gus*_*ori 19
你有几个选择:
使用SetThreadExecutionState,其中:
允许应用程序通知系统它正在使用中,从而防止系统在应用程序运行时进入睡眠状态或关闭显示屏.
你可以在哪里用ES_SYSTEM_REQUIRED
旗帜
通过重置系统空闲计时器强制系统处于工作状态.
使用SendInput伪造击键,鼠标移动/点击
SetThreadExecutionState示例
// Television recording is beginning. Enable away mode and prevent
// the sleep idle time-out.
SetThreadExecutionState(
ES_CONTINUOUS |
ES_SYSTEM_REQUIRED |
ES_AWAYMODE_REQUIRED);
// Wait until recording is complete...
// Clear EXECUTION_STATE flags to disable away mode and allow the system
// to idle to sleep normally.
SetThreadExecutionState(ES_CONTINUOUS);
Run Code Online (Sandbox Code Playgroud)
Ric*_*key 10
您可以使用SetThreadExecutionState
此处描述:
由于它是一个Win32 API函数,要从C#中使用它,你需要PInvoke它.这里描述了这些步骤,包括PreventSleep
暂时禁用睡眠模式的示例方法:
归档时间: |
|
查看次数: |
33984 次 |
最近记录: |