2

I am trying to write a small program in VB.NET that detects when my laptop has been disconnected from the power mains and switches the power plan to power saver and vice versa when it is plugged into the mains.

I tried doing it through the registry with this code snippet

Select Case power_status.ACLineStatus
            Case 0
                Dim CurrentPowerPlan As String = My.Computer.Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control").OpenSubKey("Power").OpenSubKey("User").OpenSubKey("PowerSchemes").GetValue("ActivePowerScheme")
                If CurrentPowerPlan <> "a1841308-3541-4fab-bc81-f71556f20b4a" Then
                    Label1.Text = "Running On Battery"
                    ChangePowerPlan("a1841308-3541-4fab-bc81-f71556f20b4a") 'Power Saver
                End If
            Case 1
                Dim CurrentPowerPlan As String = My.Computer.Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control").OpenSubKey("Power").OpenSubKey("User").OpenSubKey("PowerSchemes").GetValue("ActivePowerScheme")
                If CurrentPowerPlan <> "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c" Then
                    Label1.Text = "Connected To NEPA"
                    ChangePowerPlan("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c") 'High Performance
                End If
                'Case 255
                'MessageBox.Show("Unknown")
        End Select

But it throws back this error

Requested registry access is not allowed.

I also have heard of a Win32 function ``"PowerSetActiveScheme"` but i don't know how to map it to VB.NET.

jonsca
  • 4,084
Bezaleel
  • 141
  • 1
  • 1
  • 7

1 Answers1

4

You could try running a shell command from your VB.NET application to shell a command similar to the following:

powercfg -SETACTIVE {guidScheme2}

As per the information in this article about Power Schemes