如何在 C++ 中记录屏幕时间? [英] How to record screentime in c++?

查看:26
本文介绍了如何在 C++ 中记录屏幕时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 的新手,想创建一个类似于 ios for windows 的 Screentime 应用程序.但不幸的是,在使用 Visual Studio 2019 创建默认引导程序后,我被卡住了. 谁能建议我下一步应该做什么以及其他相关资源?我只是想创建一个简单的应用程序(比方说屏幕时间),它可以在屏幕时间应用程序运行时监控其他应用程序的活动和聚焦状态,并将应用程序名称、开始时间和结束时间存储在文本文件中.

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.

推荐答案

以下 Windows API 应该对此有所帮助:

The following Windows APIs should help with this:

  1. GetForegroundWindow 将返回用户当前工作的窗口.

  1. GetForegroundWindow will return the window the user is currently working in.

GetWindowThreadProcessId 将检索与该窗口对应的进程 ID.

GetWindowThreadProcessId will retrieve the process ID corresponding to that window.

此处有一个答案,其中显示了如何将进程 ID 映射到进程名称.

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.

如评论中所述,有一种更好的方法可以跟踪前景窗口何时发生变化.您可以使用 SetWinEventHook 安装处理程序以侦听此类更改,然后在处理程序中执行所需的操作.

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.

你会像这样调用 SetWinEventHook:

HWINEVENTHOOK hHook = SetWinEventHook (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND,
    NULL, MyEventHandler, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);

MyEventHandler 会像这样声明:

Where MyEventHandler would be declared like this:

void CALLBACK MyEventHandler (
  HWINEVENTHOOK hWinEventHook,
  DWORD event,
  HWND hwnd,
  LONG idObject,
  LONG idChild,
  DWORD idEventThread,
  DWORD dwmsEventTime
)
{ ... }

并且 hwnd 作为新的前景窗口传递.

And hwnd is passed as the new foreground window.

最后,将 hHook 传递给 UnhookWinEvent 在退出应用程序之前(或不再需要钩子时).

Finally, pass hHook to UnhookWinEvent before exiting your application (or when the hook is no longer needed).

这篇关于如何在 C++ 中记录屏幕时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆