Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How to check if the computer is locked/sleep?

Tags:

c

windows

Is there any function in C to check if the computer is going to sleep,hibernate or locked and waking up from these state?

In msdn they provided for C#, C++ but not for C. My OS is windows7

Like below is the code I'm using to check the time duration between starting the program and terminating it(shutting down the system will terminate the program so this way time duration can be measured).

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include<time.h>
clock_t start_time=0;
void bye (void)
{
    FILE *read,*write;
    write=fopen("F:\\count.txt","w");
    clock_t end_time=clock();
    fprintf(write,"Time: %d",(end_time-start_time)/CLOCKS_PER_SEC);
    fclose(write);
}

int main (void)
{
     start_time=clock();     
  atexit (bye);
  //exit (EXIT_SUCCESS);
  getch();
}

In the same way I want to check for locked/sleep/hibernate.

One possible way to wrap the c++ code(provided in the link) in c as mentioned by @ddriver

But is it not possible in C at all?

like image 620
Anurag Chakraborty Avatar asked Feb 10 '23 06:02

Anurag Chakraborty


2 Answers

The WinAPI has generally at least the same possibilities as .NET framework. What your are asking for is the PowerManagement API.

You will have to register to receive PowerSettingNotificationEvents with the RegisterPowerSettingNotification function. Unfortunately, it is used differently for a GUI application where you give a handle to a window that will then receive a WM_POWERBROADCAST message each time the system is about to change state (one of the suspend modes or the hibernate mode), and for a non GUI (typically a service) that registers a HandlerEx callback with a dwControl parameter of SERVICE_CONTROL_POWEREVENT and a dwEventType of PBT_POWERSETTINGCHANGE.

like image 96
Serge Ballesta Avatar answered Feb 11 '23 21:02

Serge Ballesta


The link you provide is about signals, emitted when power mode is changing. So, obviously, you can check when the system is about to go to sleep, or it just woke up.

As of checking if the system currently sleeps, that is simply not possible, as user code will simply not be running during deep sleep states. Maybe some platform specific, very low level BIOS API, but those are usually not public, and far from portable.

like image 26
dtech Avatar answered Feb 11 '23 22:02

dtech