使用Qt获取系统空闲时间

5

我是几周前开始接触Qt的新手。我试图用C++重写一个C#应用程序,并已经完成了其中的很大一部分。我目前面临的挑战是找到一种检测系统空闲时间的方法。

在我的C#应用程序中,我从某个地方偷来了以下代码:

public struct LastInputInfo
{
    public uint cbSize;
    public uint dwTime;
}

[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LastInputInfo plii);

/// <summary>
/// Returns the number of milliseconds since the last user input (or mouse movement)
/// </summary>
public static uint GetIdleTime()
{
    LastInputInfo lastInput = new LastInputInfo();
    lastInput.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInput);
    GetLastInputInfo(ref lastInput);

    return ((uint)Environment.TickCount - lastInput.dwTime);
}

我还没有学会如何通过DLL导入或C++等同方式引用Windows API函数。老实说,如果可能的话,我更愿意避免使用它们。这个应用程序将来可能会移植到Mac OSX和Linux。
是否有一种Qt特定的、平台无关的方法来获取系统空闲时间?也就是说,用户没有触摸鼠标或任何键盘按键的时间为X。
非常感谢您提供的任何帮助。
1个回答

2

由于似乎没有人知道,而且我也不确定这是否可能,所以我决定设置一个低间隔轮询计时器来检查鼠标的当前X、Y位置。我知道这不是一个完美的解决方案,但是...

  1. 它可以跨平台工作,无需进行特定于平台的操作(如DLL导入等)
  2. 它满足我需要的目的:确定某人是否正在活跃地使用系统

是的,我知道可能会有一些情况,比如某人可能没有鼠标或其他设备。我暂时称之为“低活动状态”。够好了。以下是代码:

mainwindow.h - 类声明

private:
    QPoint mouseLastPos;
    QTimer *mouseTimer;
    quint32 mouseIdleSeconds;

mainwindow.cpp - 构造函数方法

//Init
mouseTimer = new QTimer();
mouseLastPos = QCursor::pos();
mouseIdleSeconds = 0;

//Connect and Start
connect(mouseTimer, SIGNAL(timeout()), this, SLOT(mouseTimerTick()));
mouseTimer->start(1000);

mainwindow.cpp - 类主体

void MainWindow::mouseTimerTick()
{
    QPoint point = QCursor::pos();
    if(point != mouseLastPos)
        mouseIdleSeconds = 0;
    else
        mouseIdleSeconds++;

    mouseLastPos = point;

    //Here you could determine whatever to do
    //with the total number of idle seconds.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接