I am a newbie to C++ and wanted to create a Screentime application like in ios for windows. But unfortunately, I am stuck after creating the default bootstrap by using visual studio 2019. Can anyone suggest to me what I should do next and other related resources? I just wanted to create a simple app (let's say screentime) that monitors other apps active and focused state whenever the screentime app is run and store the app name, start time and end time in a text file.
-
**Programming Windows** by Charles Petzold has been the *go to* book for learning Windows programming for many Windows developers. It'll tremendously help you get underway. – Eljay Aug 10 '21 at 14:58
-
@Eljay agree that it's a well done book but there's nothing on `setwindowshookex()` there. – Алексей Неудачин Aug 10 '21 at 15:38
1 Answers
The following Windows APIs should help with this:
GetForegroundWindowwill return the window the user is currently working in.GetWindowThreadProcessIdwill retrieve the process ID corresponding to that window.There's an answer here which shows how to map the process ID to a process name.
It's then a matter of doing this periodically on a timer to keep track of the current application and logging the results.
As noted in the comments, there is a better way to track when the foreground window changes. You can use SetWinEventHook to install a handler to listen for such changes and then take the desired action in your handler when it does.
You would call SetWinEventHook like this:
HWINEVENTHOOK hHook = SetWinEventHook (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND,
NULL, MyEventHandler, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
Where MyEventHandler would be declared like this:
void CALLBACK MyEventHandler (
HWINEVENTHOOK hWinEventHook,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD idEventThread,
DWORD dwmsEventTime
)
{ ... }
And hwnd is passed as the new foreground window.
Finally, pass hHook to UnhookWinEvent before exiting your application (or when the hook is no longer needed).
- 594
- 1
- 6
- 20
- 24,133
- 4
- 26
- 48
-
https://stackoverflow.com/questions/20618720/is-there-any-system-event-which-fires-when-getforegroundwindow-changes How i said early haha – Алексей Неудачин Aug 10 '21 at 15:50
-
[SetWinEventHook](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook) is the correct way to do this. No need to periodically ask *"Are we there yet?"*. Just have the system set an alarm for you, and you won't sleep right through the interesting parts. – IInspectable Aug 10 '21 at 16:22