CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Join Date
    Sep 2010
    Posts
    10

    Exclamation Know when laptop lid is closed

    Hi,

    I have a laptop with windows 7 and I am trying to make a program for it. I want it to do is after a certain time of day when I close the lid of my laptop it will make it go to sleep. But at every other time of the day I want it to stay awake when I close the lid.

    I have been looking all over the internet and i don't understand what people are saying.

    If anyone can tell me a way of knowing when my laptops lid is closed in vb.net that would be fantastic.

    Any help, code, instructions would be great.

    Thanks in advanced.

    JamesStewy

  2. #2
    Join Date
    Feb 2000
    Location
    OH - USA
    Posts
    1,892

    Arrow Re: Know when laptop lid is closed

    There is no Windows API for this that I know of. You would probably have to monitor the power status through WMI if anything.
    Good Luck,
    Craig - CRG IT Solutions - Microsoft Gold Partner

    -My posts after 08/2015 = .NET 4.x and Visual Studio 2015
    -My posts after 11/2011 = .NET 4.x and Visual Studio 2012
    -My posts after 02/2010 = .NET 4.0 and Visual Studio 2010
    -My posts after 12/2007 = .NET 3.5 and Visual Studio 2008
    -My posts after 04/2007 = .NET 3.0 and Visual Studio 2005
    -My posts before 04/2007 = .NET 1.1/2.0

    *I do not follow all threads, so if you have a secondary question, message me.

  3. #3
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Hi,

    Thanks for your reply.

    I am just not quite sure what you are saying, i am quite new to vb.

    Thanks again for your reply


    JamesStewy

  4. #4
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Know when laptop lid is closed

    I saw your post in other forums too, and it does seem to be a decent question, with no direct solution.

    As others have pointed out you can detect the power status change in a few ways. The power settings in your control panel, are important to how you handle the change.

    A professional would also check to see if the monitor power changes too. This event usually happens when you close your lid, even if you've specified it to do nothing.

    For example, I just checked my laptop, and it is set to do nothing.
    However, the monitor power does go out just before the lid is fully closed.

  5. #5
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Great, Thanks TT(n).

    But as i said I am not the greatest vb programer on earth and if you could give me some code to play with that would help a lot thanks.

    JamesStewy

  6. #6
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Know when laptop lid is closed

    This is something for an advanced programmer, and we can tell you need help. If it were easy or straight forward, you'd have your full answer by now.

    Here is some code to detect session changes:
    Code:
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            AddHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf SysSuspend
            AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf SysLogOff
            AddHandler Microsoft.Win32.SystemEvents.SessionSwitch, AddressOf SysSwitch
            AddHandler Microsoft.Win32.SystemEvents.SessionEnded, AddressOf SysLoggedOff
            AddHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf StatusChange
        End Sub
    
        Public Sub SysLogOff(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
            If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
                MessageBox.Show("user logging off")
            ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
                MessageBox.Show("system is shutting down")
            End If
        End Sub
        Public Sub SysLoggedOff(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndedEventArgs)
            If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
                MessageBox.Show("user logged off")
            ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
                MessageBox.Show("system has shut down")
            End If
        End Sub
        Public Sub SysSwitch(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionSwitchEventArgs)
            If e.Reason = Microsoft.Win32.SessionSwitchReason.ConsoleConnect Then
                MessageBox.Show("Console connect")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.ConsoleDisconnect Then
                MessageBox.Show("Console disconnect")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.RemoteConnect Then
                MessageBox.Show("Remote Connect")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.RemoteDisconnect Then
                MessageBox.Show("Remote Disconnect")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.SessionLock Then
                MessageBox.Show("Session Lock")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.SessionLogoff Then
                MessageBox.Show("Session Logoff")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.SessionLogon Then
                MessageBox.Show("Session Logon")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.SessionRemoteControl Then
                MessageBox.Show("Session Remote Control")
            ElseIf e.Reason = Microsoft.Win32.SessionSwitchReason.SessionUnlock Then
                MessageBox.Show("Session Unlock", "", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification)
            End If
        End Sub
        Public Sub SysSuspend(ByVal sender As Object, ByVal e As Microsoft.Win32.PowerModeChangedEventArgs)
            If e.Mode = Microsoft.Win32.PowerModes.Resume Then
                MessageBox.Show("system is resuming")
            ElseIf e.Mode = Microsoft.Win32.PowerModes.Suspend Then
                MessageBox.Show("system being suspended")
            ElseIf e.Mode = Microsoft.Win32.PowerModes.StatusChange Then
                MessageBox.Show("system has a status change")
            End If
        End Sub
    
        Public Sub StatusChange(ByVal sender As Object, ByVal e As Microsoft.Win32.PowerModeChangedEventArgs)
            If e.Mode = Microsoft.Win32.PowerModes.StatusChange Then
                MessageBox.Show("Battery status has changed")
            End If
        End Sub
    You'll probably be interested in System Suspend, or Session Lock, if you have your power option set to "Standby".
    If you have a windows password then it will also lock the session out, which may complicate things even more.
    I will have to look into it some more over the weekend.

  7. #7
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Hi,

    That code is great and it works but can you make like a function to tell the monitor power state.

    I saw this code on the internet

    Public Function IsMonitorOff() As Boolean

    On Error GoTo Hell

    Dim wmiObjSet As SWbemObjectSet
    Dim colSettings As SWbemObject
    wmiObjSet = GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf("Win32_DesktopMonitor")

    For Each colSettings In wmiObjSet
    MsgBox(colSettings.Availability)
    Select Case colSettings.Availability
    Case 7
    IsMonitorOff = True
    Case 3
    IsMonitorOff = False
    End Select
    Next
    Exit_For:
    wmiObjSet = Nothing
    On Error GoTo 0
    Exit Function

    Hell:
    GoTo Exit_For
    End Function

    But the SWbemObjectSet and SWbemObject aren't decared and i can't find any on the internet.

    JamesStewy

  8. #8
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Know when laptop lid is closed

    Download PowerShell Scriptomatic, and it tells you this result (for my laptop)



    __GENUS : 2
    __CLASS : Win32_DesktopMonitor
    __SUPERCLASS : CIM_DesktopMonitor
    __DYNASTY : CIM_ManagedSystemElement
    __RELPATH : Win32_DesktopMonitor.DeviceID="DesktopMonitor1"
    __PROPERTY_COUNT : 28
    __DERIVATION : {CIM_DesktopMonitor, CIM_Display, CIM_UserDevice,
    CIM_LogicalDevice...}
    __SERVER : ASUSVISTA
    __NAMESPACE : root\CIMV2
    __PATH : \\.\root\CIMV2:Win32_DesktopMonitor.Devic
    eID="DesktopMonitor1"
    Availability : 3
    Bandwidth :
    Caption : Generic PnP Monitor
    ConfigManagerErrorCode : 0
    ConfigManagerUserConfig : False
    CreationClassName : Win32_DesktopMonitor
    Description : Generic PnP Monitor
    DeviceID : DesktopMonitor1
    DisplayType :
    ErrorCleared :
    ErrorDescription :
    InstallDate :
    IsLocked :
    LastErrorCode :
    MonitorManufacturer : (Standard monitor types)
    MonitorType : Generic PnP Monitor
    Name : Generic PnP Monitor
    PixelsPerXLogicalInch : 96
    PixelsPerYLogicalInch : 96
    PNPDeviceID : DISPLAY\AUO5044\5&87CAC5E&1&UID16777488
    PowerManagementCapabilities :
    PowerManagementSupported :
    ScreenHeight : 800
    ScreenWidth : 1280
    Status : OK
    StatusInfo :
    SystemCreationClassName : Win32_ComputerSystem
    SystemName : xxxxx

    and the actual script:
    Code:
    $computer = "LocalHost" 
    $namespace = "root\CIMV2" 
    Get-WmiObject -class Win32_DesktopMonitor -computername $computer -namespace $namespace
    The old version, Scriptomatic2 will write VBA code, but that won't run on Windows 7 x64.

    If you get that to run, it will give you the code.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  9. #9
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Hi dglienna,

    Thanks for your reply. Which of the property things that come up is the one that tells me if my monitor has powered off. Also how do I implement it into my vb program.

    Bye the way I am using windows 7 x32.

    JamesStewy
    Last edited by JamesStewy; October 2nd, 2010 at 03:12 AM. Reason: Realised my mistake

  10. #10
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Know when laptop lid is closed

    See if Scriptomatic2 runs, or get Powershell. You can install that on any OS. Might have Powershell 1 on Windows 7 by default. I forget.

    Powershell Scriptomatic writes scripts that you can execute FROM your program.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  11. #11
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Ok, just a few things.

    So I have to save the script in ScriptOmatic? If so what is the file extension?
    Which of the property that come up is the one that tells me if my monitor has powered off?

    JamesStewy

  12. #12
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Know when laptop lid is closed

    Search for THE SCRIPTING GUYS from Microsoft. They've written both versions AFIK
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  13. #13
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Know when laptop lid is closed

    This works on my desktop, but I have not tested the laptop yet.

    Code:
        Const WM_SYSCOMMAND As Int32 = 274
        Const SC_MONITORPOWER As Int32 = 61808
    
        Protected Overrides Sub WndProc(ByRef m As Message)
    
            If m.Msg = WM_SYSCOMMAND Then 'Intercept System Command
                ' notice the 0xFFF0 mask, it's because the system can use the 4 low order bits of the wParam value as stated in the MSDN library article about WM_SYSCOMMAND. 
    
                If (m.WParam.ToInt32() And &HFFF0) = SC_MONITORPOWER Then 'Intercept Monitor Power Message
                    Dim s As String = "Power status has changed for the display monitor "
                    If m.LParam.ToInt32 = -1 Then
                        s &= "On"
                    ElseIf m.LParam.ToInt32 = 1 Then
                        s &= "Standby"
                    ElseIf m.LParam.ToInt32 = 2 Then
                        s &= "Off"
                    End If
                    MessageBox.Show(s)
                End If
    
            End If
            MyBase.WndProc(m)
        End Sub
    We might be able to resolve this thread afterall.
    There at least three ways to do this, and the other two do use API's.
    One is similar to above but uses the APIs CallWindowProc and SetWindowLong, with the constants WM_SYSCOMMAND and SC_MONITORPOWER, along with the needed delegate.
    The other works on Vista/7 only, using WM_POWERBROADCAST basically.
    Last edited by TT(n); October 3rd, 2010 at 08:43 AM. Reason: extra lower param state

  14. #14
    Join Date
    Sep 2010
    Posts
    10

    Re: Know when laptop lid is closed

    Hi Again,

    I am back to school now so i can only really reply on weekends.

    I tested the code and it never passes this line

    If (m.WParam.ToInt32() And &HFFF0) = SC_MONITORPOWER Then

    (m.WParam.ToInt32() And &HFFF0) never equals SC_MONITORPOWER.

    JamesStewy

  15. #15
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Know when laptop lid is closed

    Show us this before the IF
    Code:
    msgbox(m.WParam.ToInt32()))
    or even

    Code:
    msgbox(m.WParam.ToInt32)
    or

    Code:
    debug.print m.WParam.ToInt32
    Might have been AFPC
    Last edited by dglienna; October 8th, 2010 at 07:31 PM.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

Page 1 of 2 12 LastLast

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

Featured