WinForm 指定时间没有操作键盘鼠标,弹出屏幕保护

 #region 屏幕保护
 System.Timers.Timer timerRunScreenSaverTask = null;
 F_ScreenSaver f_ScreenSaver = null;
 private void RunScreenSaverTask() 
 {
     if (timerRunScreenSaverTask == null)
     {
         timerRunScreenSaverTask = new System.Timers.Timer();
         timerRunScreenSaverTask.Interval = 1000;
         timerRunScreenSaverTask.Elapsed += TimerRunScreenSaverTask_Elapsed;
         timerRunScreenSaverTask.Start();
     }
 }

 private void TimerRunScreenSaverTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     RunScreenSaver();
 }

 private void RunScreenSaver() 
 {
     long lastInputTimeToNow = GetLastInputTime();
     if (lastInputTimeToNow >= 5 * 1000)
     {
         Console.WriteLine("走If分支" + "空闲时间" + lastInputTimeToNow.ToString());
         string imagePath = Application.StartupPath + @"\Update\ScreenSaver.png";
         if (File.Exists(imagePath) == false)
         {
             return;
         }

         if (f_ScreenSaver == null)
         {
             f_ScreenSaver = new F_ScreenSaver();
             f_ScreenSaver.TopLevel = true;
             f_ScreenSaver.ShowDialog();
         }
         else
         {
             f_ScreenSaver.ShowDialog();
         }
     }
     else
     {
         Console.WriteLine("走else分支" + "空闲时间" + lastInputTimeToNow.ToString());
         if (f_ScreenSaver != null)
         {
             f_ScreenSaver.Hide();
         }
     }
 }

 [DllImport("user32.dll")]
 static extern bool GetLastInputInfo(ref LastInputInfo plii);
 static long GetLastInputTime()
 {
     LastInputInfo vLastInputInfo = new LastInputInfo();
     vLastInputInfo.Size = Marshal.SizeOf(vLastInputInfo);
     if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
     return Environment.TickCount - (long)vLastInputInfo.Time;
 }

 [StructLayout(LayoutKind.Sequential)]
 struct LastInputInfo
 {
     [MarshalAs(UnmanagedType.U4)]
     public int Size;
     [MarshalAs(UnmanagedType.U4)]
     public uint Time;
 }
 #endregion

 

posted @ 2024-03-18 10:50  chengeng  阅读(56)  评论(0编辑  收藏  举报