Thursday, April 9

Console app to keep screensaver from activating

Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Module Module1

    
    Public Enum EXECUTION_STATE As UInteger
        ES_SYSTEM_REQUIRED = &H1
        ES_DISPLAY_REQUIRED = &H2
        ES_CONTINUOUS = &H80000000UI
    End Enum

    
    Private Function SetThreadExecutionState(ByVal esFlags As EXECUTION_STATE) As EXECUTION_STATE
    End Function

    Public Sub ContinuousDisplayRequired()
        SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS Or EXECUTION_STATE.ES_SYSTEM_REQUIRED)
    End Sub

    Dim aTimer As New System.Timers.Timer
    Sub Main()
        Dim CurrentProcess As Process = Process.GetCurrentProcess()
        Dim CopiesOfThisProcess() As Process = Process.GetProcessesByName(CurrentProcess.ProcessName)
        For Each CopyOfThisProcess As System.Diagnostics.Process In CopiesOfThisProcess
            If (CopyOfThisProcess.StartTime <> CurrentProcess.StartTime) Then
                CopyOfThisProcess.Kill() 'Kill all other instances of this process
            End If
        Next CopyOfThisProcess
        Console.WindowLeft = 0
        Console.WindowTop = 0
        Console.WindowWidth = Console.LargestWindowWidth \ 10
        Console.WindowHeight = Console.LargestWindowHeight \ 2
        Console.WriteLine(Now.ToString("yyyy-MM-dd HH:mm:ss"))
        Console.Title = Now.ToString("HH:mm:ss")
        Application.DoEvents()
        aTimer.AutoReset = True
        aTimer.Interval = 1000 '1 second
        AddHandler aTimer.Elapsed, AddressOf TimerIntervalElapsed
        aTimer.Start()
        Console.ReadKey()
    End Sub

    Private Sub TimerIntervalElapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
        aTimer.Enabled = False
        If Now.ToString("HH:mm:ss") > "15:00:00" Then
            End
        End If
        Console.WriteLine(Now.ToString("yyyy-MM-dd HH:mm:ss"))
        aTimer.Interval = GetRandomNumber(60000, 300000) 'Minimum and maximum time to next interval in milliseconds
        Console.Title = DateAndTime.DateAdd(DateInterval.Second, aTimer.Interval \ 1000, Now).ToString("hh:mm:ss")
        'Try
        '    System.Windows.Forms.SendKeys.SendWait("^+{SCROLLLOCK 2}")
        ContinuousDisplayRequired()
        'Catch
        '    Application.Restart()
        'End Try
        aTimer.Enabled = True
        Application.DoEvents()
    End Sub

    Public Function GetRandomNumber(ByVal Min As Integer, ByVal Max As Integer) As Integer
        Static Generator As New System.Random
        Return Generator.Next(Min, Max)
    End Function

End Module