Results 1 to 3 of 3

Thread: How to learn monitor off status with code

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    226

    How to learn monitor off status with code

    I am trying to make a program that calculates the system active time amount. This program would calculate the total amount of system active time and idle time. From power options monitor turn off display status. How can we learn if the monitor is on or off with code. If there is a program that can show the window active time amount so that I will not create a program from beginning
    Thanks in advance

  2. #2
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: How to learn monitor off status with code

    Quote Originally Posted by algea View Post
    How can we learn if the monitor is on or off with code.
    EDIT: Think I misread that question, I was thinking of "off" as sleep mode, I don't turn off my displays.

    I could be totally wrong but, I think to detect that you'll need to get the users display sleep setting and then subtract that from their current idle time.

    The following is a google/copy&paste effort using that idea, and is working as expected on my single monitor Win7 desktop.
    Code:
    Imports System.Runtime.InteropServices
    Public Class Form1
        ' start timer to show seconds until display goes to sleep.
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Timer1.Interval = 1000
            Timer1.Start()
        End Sub
    
        Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
            ' get user idle time in seconds
            Dim idleTime = GetSecondsIdle()
            If idleTime > 0 Then
                ' get power policy
                Dim gpp As New GLOBAL_POWER_POLICY()
                Dim pp As New POWER_POLICY()
                Dim result As Boolean = Power_NativeMethods.GetCurrentPowerPolicies(gpp, pp)
                If result Then
                    ' testing on Win7 desktop w/single monitor set to sleep in 5 mins.
                    Dim monitorIdleSleepSeconds = pp.user.VideoTimeoutAc ' display sleep setting is returned in seconds?
                    ' subtract current user idle time from monitor idle time setting.
                    Me.Text = "Monitor sleeps in " & (monitorIdleSleepSeconds - idleTime).ToString & " seconds."
                Else
                    Timer1.Stop()               
                    MessageBox.Show("Get POWER_POLICY failed! :(")
                End If
            Else
                Me.Text = Me.Name
            End If
        End Sub
    
    #Region "API - Get user idle time"
        <StructLayout(LayoutKind.Sequential)> _
        Structure LASTINPUTINFO
            <MarshalAs(UnmanagedType.U4)> Public cbSize As Integer
            <MarshalAs(UnmanagedType.U4)> Public dwTime As Integer
        End Structure
    
        <DllImport("user32.dll")> _
        Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
        End Function
    
        ' Gets user idle time in secs.
        Function GetSecondsIdle() As Integer
            Dim oPLII As LASTINPUTINFO
            oPLII.cbSize = Marshal.SizeOf(oPLII)
            GetLastInputInfo(oPLII)
            'Return idle time in secs.
            Return (Environment.TickCount - oPLII.dwTime) \ 1000
        End Function
    #End Region
    
    End Class
    Code:
    ' original source , http://www.experts-exchange.com/questions/26372366/How-do-I-get-set-the-Power-Scheme-in-C.html
    Imports System.Runtime.InteropServices
    Module Module1
        Friend Class Power_NativeMethods
            <DllImport("powrprof.dll", SetLastError:=True)> _
            Friend Shared Function GetCurrentPowerPolicies(ByRef pGlobalPowerPolicy As GLOBAL_POWER_POLICY, ByRef pPowerPolicy As POWER_POLICY) As <MarshalAs(UnmanagedType.Bool)> Boolean
            End Function
        End Class
    
        <StructLayout(LayoutKind.Sequential, Pack:=1)> _
        Structure GLOBAL_POWER_POLICY
            Public UserPolicy As GLOBAL_USER_POWER_POLICY
            Public MachinePolicy As GLOBAL_MACHINE_POWER_POLICY
        End Structure
    
        <Flags()> _
        Enum GlobalPowerPolicyFlags As UInteger
            EnableSysTrayBatteryMeter = &H1
            EnableMultiBatteryDisplay = &H2
            EnablePasswordAtLogon = &H4
            EnableWakeOnRing = &H8
            EnableVideoDimDisplay = &H10
        End Enum
    
        <StructLayout(LayoutKind.Sequential, Pack:=1)> _
        Structure GLOBAL_USER_POWER_POLICY
            Public Const NUM_DISCHARGE_POLICIES As Integer = 4
            Public Revision As UInteger
            Public PowerButtonAc As POWER_ACTION_POLICY
            Public PowerButtonDc As POWER_ACTION_POLICY
            Public SleepButtonAc As POWER_ACTION_POLICY
            Public SleepButtonDc As POWER_ACTION_POLICY
            Public LidCloseAc As POWER_ACTION_POLICY
            Public LidCloseDc As POWER_ACTION_POLICY
            <MarshalAs(UnmanagedType.ByValArray, SizeConst:=NUM_DISCHARGE_POLICIES)> _
            Public DischargePolicy As SYSTEM_POWER_LEVEL()
            Public GlobalFlags As GlobalPowerPolicyFlags
        End Structure
    
        <StructLayout(LayoutKind.Sequential, Pack:=1)> _
        Structure GLOBAL_MACHINE_POWER_POLICY
            Public Revision As UInteger
            Public LidOpenWakeAc As SYSTEM_POWER_STATE
            Public LidOpenWakeDc As SYSTEM_POWER_STATE
            Public BroadcastCapacityResolution As UInteger
        End Structure
    
        <StructLayout(LayoutKind.Sequential, Pack:=1)> _
        Structure SYSTEM_POWER_LEVEL
            Public Enable As Boolean
            <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _
            Public Spare As Byte()
            Public BatteryLevel As UInteger
            Public PowerPolicy As POWER_ACTION_POLICY
            Public MinSystemState As SYSTEM_POWER_STATE
        End Structure
    
        Enum SYSTEM_POWER_STATE
            PowerSystemUnspecified = 0
            PowerSystemWorking = 1
            PowerSystemSleeping1 = 2
            PowerSystemSleeping2 = 3
            PowerSystemSleeping3 = 4
            PowerSystemHibernate = 5
            PowerSystemShutdown = 6
            PowerSystemMaximum = 7
        End Enum
    
        Enum POWER_ACTION As UInteger
            PowerActionNone = 0
            ' No system power action. 
            PowerActionReserved
            ' Reserved; do not use. 
            PowerActionSleep
            ' Sleep. 
            PowerActionHibernate
            ' Hibernate. 
            PowerActionShutdown
            ' Shutdown. 
            PowerActionShutdownReset
            ' Shutdown and reset. 
            PowerActionShutdownOff
            ' Shutdown and power off. 
            PowerActionWarmEject
            ' Warm eject.
        End Enum
    
        <Flags()> _
        Enum PowerActionFlags As UInteger
            POWER_ACTION_QUERY_ALLOWED = &H1
            ' Broadcasts a PBT_APMQUERYSUSPEND event to each application to request permission to suspend operation.
            POWER_ACTION_UI_ALLOWED = &H2
            ' Applications can prompt the user for directions on how to prepare for suspension. Sets bit 0 in the Flags parameter passed in the lParam parameter of WM_POWERBROADCAST.
            POWER_ACTION_OVERRIDE_APPS = &H4
            ' Ignores applications that do not respond to the PBT_APMQUERYSUSPEND event broadcast in the WM_POWERBROADCAST message.
            POWER_ACTION_LIGHTEST_FIRST = &H10000000
            ' Uses the first lightest available sleep state.
            POWER_ACTION_LOCK_CONSOLE = &H20000000
            ' Requires entry of the system password upon resume from one of the system standby states.
            POWER_ACTION_DISABLE_WAKES = &H40000000
            ' Disables all wake events.
            POWER_ACTION_CRITICAL = &H80000000UI
            ' Forces a critical suspension.
        End Enum
    
        <Flags()> _
        Enum PowerActionEventCode As UInteger
            POWER_LEVEL_USER_NOTIFY_TEXT = &H1
            ' User notified using the UI. 
            POWER_LEVEL_USER_NOTIFY_SOUND = &H2
            ' User notified using sound. 
            POWER_LEVEL_USER_NOTIFY_EXEC = &H4
            ' Specifies a program to be executed. 
            POWER_USER_NOTIFY_BUTTON = &H8
            ' Indicates that the power action is in response to a user power button press. 
            POWER_USER_NOTIFY_SHUTDOWN = &H10
            ' Indicates a power action of shutdown/off.
            POWER_FORCE_TRIGGER_RESET = &H80000000UI
            ' Clears a user power button press. 
        End Enum
    
        <StructLayout(LayoutKind.Sequential, Pack:=1)> _
        Structure POWER_ACTION_POLICY
            Public Action As POWER_ACTION
            Public Flags As PowerActionFlags
            Public EventCode As PowerActionEventCode
        End Structure
    
        Structure POWER_POLICY
            Public user As USER_POWER_POLICY
            Public mach As MACHINE_POWER_POLICY
        End Structure
    
        Structure MACHINE_POWER_POLICY
            Private Revision As UInteger
            Private MinSleepAc As SYSTEM_POWER_STATE
            Private MinSleepDc As SYSTEM_POWER_STATE
            Private ReducedLatencySleepAc As SYSTEM_POWER_STATE
            Private ReducedLatencySleepDc As SYSTEM_POWER_STATE
            Private DozeTimeoutAc As UInteger
            Private DozeTimeoutDc As UInteger
            Private DozeS4TimeoutAc As UInteger
            Private DozeS4TimeoutDc As UInteger
            Private MinThrottleAc As Byte
            Private MinThrottleDc As Byte
            <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _
            Private pad1 As Byte()
            Private OverThrottledAc As POWER_ACTION_POLICY
            Private OverThrottledDc As POWER_ACTION_POLICY
        End Structure
    
        <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
        Structure USER_POWER_POLICY
            Public Revision As UInteger
            Public IdleAc As POWER_ACTION_POLICY
            Public IdleDc As POWER_ACTION_POLICY
            Public IdleTimeoutAc As UInteger
            Public IdleTimeoutDc As UInteger
            Public IdleSensitivityAc As Byte
            Public IdleSensitivityDc As Byte
            Public ThrottlePolicyAc As Byte
            Public ThrottlePolicyDc As Byte
            Public MaxSleepAc As SYSTEM_POWER_STATE
            Public MaxSleepDc As SYSTEM_POWER_STATE
            <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _
            Public Reserved As UInteger()
            Public VideoTimeoutAc As UInteger
            Public VideoTimeoutDc As UInteger
            Public SpindownTimeoutAc As UInteger
            Public SpindownTimeoutDc As UInteger
            <MarshalAs(UnmanagedType.I1)> _
            Public OptimizeForPowerAc As Boolean
            <MarshalAs(UnmanagedType.I1)> _
            Public OptimizeForPowerDc As Boolean
            Public FanThrottleToleranceAc As Byte
            Public FanThrottleToleranceDc As Byte
            Public ForcedThrottleAc As Byte
            Public ForcedThrottleDc As Byte
        End Structure
    
    End Module
    Last edited by Edgemeal; Feb 2nd, 2016 at 07:06 PM.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Mar 2010
    Posts
    226

    Re: How to learn monitor off status with code

    Sorry I could not run your code. But l have found an API for what I’m about to do. Here is the code:
    Code:
    Imports System.Runtime.InteropServices
    Public Class Form1
        <StructLayout(LayoutKind.Sequential)>
        Structure LASTINPUTINFO
            <MarshalAs(UnmanagedType.U4)>
            Public cbSize As Integer
            <MarshalAs(UnmanagedType.U4)>
            Public dwTime As Integer
        End Structure
        <DllImport("user32.dll")>
        Shared Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean
        End Function
    
        Dim idletime As Integer
        Dim lastInputInf As New LASTINPUTINFO()
        Public Function GetLastInputTime() As Integer
            idletime = 0
            lastInputInf.cbSize = Marshal.SizeOf(lastInputInf)
            lastInputInf.dwTime = 0
    
            If GetLastInputInfo(lastInputInf) Then
                idletime = Environment.TickCount - lastInputInf.dwTime
            End If
    
            If idletime > 0 Then
                Return idletime / 1000
            Else : Return 0
            End If
        End Function
    
        Private sumofidletime As TimeSpan = New TimeSpan(0)
        Private LastLastIdletime As Integer = 0
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Dim it As Integer = GetLastInputTime()
            If LastLastIdletime > it Then
                Label1.Text = "IDLE STATE CHANGED!"
                sumofidletime = sumofidletime.Add(TimeSpan.FromSeconds(LastLastIdletime))
                Label2.Text = "Sum of idle time: " & sumofidletime.ToString
            Else
                Label1.Text = GetLastInputTime()
            End If
            LastLastIdletime = it
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
            Timer1.Interval = 1000
            Timer1.Enabled = True
        End Sub
    End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width