I'm developing an app using Electron and Node.js and is supposed to set the laptop (running windows 10) to energy saving mode when needed, is this possible to do this using technologies of Node.js and electron? Thanks
问题:
回答1:
You can call the WinAPI function SetSuspendState
using the node-ffi
library.
First, install the library:
npm install ffi --save
Then, you can use this code:
var ffi = require('ffi');
var powrprof = ffi.Library('powrprof.dll', {
SetSuspendState: ['int', ['int', 'int', 'int']]
});
function invokeStandby() {
powrprof.SetSuspendState(0, 0, 0);
}
Note that this does a normal standby and leaves wake events on. If you want to disable wake events, use powrprof.SetSuspendState(0, 0, 1)
(third parameter 1 instead of 0). See the docs for details.
UPDATE: Note that if you think a nice shortcut would be using rundll32
, then you will get weird behavior depending on the computer settings and probably the weather and the day of week (as in - undefined behavior), because rundll32
doesn't just run arbitrary DLL functions the way you think. See this article and the rundll32
docs. Calling rundll32 powrprof.dll,SetSuspendState 0,0,0
might put your computer to sleep, but it might do something else on another computer such as hibernating instead of invoking standby mode (or theoretically even crash). So, do not do this!
回答2:
I came up with an idea which doesn't require additional libraries.
var exec = require('child_process').exec;
exec('rundll32.exe powrprof.dll,SetSuspendState 0,0,0');
This function simply spawns a shell calling rundll32.exe so we can directly execute the function SetSuspendState
with the required parameters.
Hope this helps