Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting System Idle Time with Qt

I'm new to Qt as of a few weeks ago. I'm trying to rewrite a C# application with C++ and have a good portion of it figure now. My current challenge is finding a way to detect the system idle time.

With my C# application, I stole code from somewhere that looks like this:

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);
}

I haven't yet learned how to reference Windows API functions through DLL Imports or whatever the C++ equivalent is. Honestly, I would prefer to avoid them if possible. This application is moving to Mac OSX and possibly Linux in the future as well.

Is there a Qt specific, platform-independent way to get the system idle-time? Meaning the user has not touched the mouse or any keys for X amount of time.

Thanks you in advance for any help you can provide.

like image 632
jocull Avatar asked Nov 05 '22 08:11

jocull


1 Answers

Since no one seems to know, and I'm not sure that this is even possible, I decided to setup a low interval polling timer to check the current X, Y of the mouse. I know it's not a perfect solution, but...

  1. It will work cross platform without me doing platform specific things (like DLL imports, yuck)
  2. It serves the purpose I need it for: determining if someone is actively using the system or not

Yes, yes, I know there could be situations where someone may not have a mouse or whatever. I'm calling that a "low activity state" for now. Good enough. Here is the code:

mainwindow.h - Class declaration

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

mainwindow.cpp - Constructor method

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

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

mainwindow.cpp - Class body

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.
}
like image 134
jocull Avatar answered Nov 11 '22 04:11

jocull