判断桌面是否处于屏保,其他屏保操作可参考
(https://www.codeproject.com/Articles/17067/Controlling-The-Screen-Saver-With-C)
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SystemParametersInfo(
int uAction, int uParam, ref bool lpvParam,
int flags);
private const int SPI_GETSCREENSAVERRUNNING = 114; //获取是否处于屏保参数
/// <summary>
/// 桌面是否处于屏保
/// </summary>
/// <returns></returns>
public static bool IsScreenSaverRunning()
{
bool isRunning = false;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, ref isRunning, 0);
return isRunning;
}
监听系统解锁屏、登录和注销事件
/// <summary>
/// 当前登录的用户变化(登录、注销和解锁屏)
/// </summary>
class SessionSwitchClass
{
/// <summary>
/// 解屏后执行的委托
/// </summary>
public Action SessionUnlockAction { get; set; }
/// <summary>
/// 锁屏后执行的委托
/// </summary>
public Action SessionLockAction { get; set; }
public SessionSwitchClass()
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
}
//析构,防止句柄泄漏
~SessionSwitchClass()
{
//Do this during application close to avoid handle leak
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
//当前登录的用户变化(登录、注销和解锁屏)
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
switch (e.Reason)
{
//用户登录
case SessionSwitchReason.SessionLogon:
BeginSessionUnlock();
break;
//解锁屏
case SessionSwitchReason.SessionUnlock:
BeginSessionUnlock();
break;
//锁屏
case SessionSwitchReason.SessionLock:
BeginSessionLock();
break;
//注销
case SessionSwitchReason.SessionLogoff:
break;
}
}
/// <summary>
/// 解屏、登录后执行
/// </summary>
private void BeginSessionUnlock()
{
//解屏、登录后执行
}
/// <summary>
/// 锁屏后执行
/// </summary>
private void BeginSessionLock()
{
//锁屏后执行
}
}