我遇到一个自定义事件的问题,该事件会启动屏幕保护程序开启/关闭事件,当程序启动并且我的屏幕保护程序打开时,我的程序没有触发事件的屏幕保护程序!
我的代码如下,任何和所有帮助将不胜感激=]
class ScreensaverStatusWatcher
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(int uAction, int uParam, ref int ipvParam, int fuWinini);
private const int screenSaverRunningStartup = -1;
const int SPI_GETSCREENSAVERRUNNING = 114;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private bool ScreensaverStatus = false;
private readonly System.Timers.Timer timer = new System.Timers.Timer();
public int Interval { get; set; }
public event EventHandler<EventArgs> ScreensaverOn;
public event EventHandler<EventArgs> ScreensaverOff;
public ScreensaverStatusWatcher()
{
timer.Interval = 1000 * 5;
this.Initialize();
}
public ScreensaverStatusWatcher(int interval)
{
timer.Interval = interval;
this.Initialize();
}
private void Initialize()
{
timer.Elapsed += timer_Elapsed;
}
public void Start()
{
timer.Start();
}
public void Stop()
{
timer.Stop();
}
public bool IsScreenSaverRunning()
{
int screenSaverRunning = -1;
int ok = SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, ref screenSaverRunning, 0);
//return - on fail
if (ok == 0)
{
return false;
}
return (screenSaverRunning != 0);
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (!this.ScreensaverStatus && this.IsScreenSaverRunning())
{
this.ScreensaverStatus = true;
this.OnScreensaverOn(new EventArgs());
}
else if(this.ScreensaverStatus && !this.IsScreenSaverRunning())
{
this.ScreensaverStatus = false;
this.OnScreensaverOff(new EventArgs());
}
}
private void OnScreensaverOn(EventArgs e)
{
if (this.ScreensaverOn != null)
{
this.ScreensaverOn(this, e);
}
}
private void OnScreensaverOff(EventArgs e)
{
if (this.ScreensaverOff != null)
{
this.ScreensaverOff(this, e);
}
}
}
}
更新 这是使用此类的代码
private ScreensaverStatusWatcher watcher = new ScreensaverStatusWatcher();
void watcher_ScreensaverOn(object sender, EventArgs e)
{
var data = LogDataFactory.CollectData();
data.EventType = UserStateEvents.ScreensaverOn;
PublishLogData(data);
}
void watcher_ScreensaverOff(object sender, EventArgs e)
{
var data = LogDataFactory.CollectData();
data.EventType = UserStateEvents.ScreensaverOff;
PublishLogData(data);
答案 0 :(得分:0)
除非您没有向我们展示某些代码,否则您不会在任何地方调用Start方法来设置计时器运行。因此,Elapsed事件永远不会触发,因此您永远不会读取屏幕保护程序的状态。