Ejemplo n.º 1
0
static void __cdecl FlashThreadFunction(void*)
{
	BOOL bEvent = FALSE;
	DWORD dwEventStarted = 0, dwFlashStarted = 0;
	BYTE data, unchangedLeds;

	while (TRUE) {
		unchangedLeds = (BYTE)(LedState(VK_PAUSE) * !bFlashLed[2] + ((LedState(VK_NUMLOCK) * !bFlashLed[0]) << 1) + ((LedState(VK_CAPITAL) * !bFlashLed[1]) << 2));
		GetAsyncKeyState(VK_PAUSE); // empty Pause/Break's keystroke buffer

		// Start flashing
		while (bEvent && bFlashingEnabled) {
			// Let's give the user the opportunity of finishing flashing manually :)
			if (GetAsyncKeyState(VK_PAUSE) & 1)
				break;

			if ((bFlashUntil & UNTIL_NBLINKS) && GetTickCount() > (dwFlashStarted + wBlinksNumber * 1000))
				break;
			if (bFlashUntil & UNTIL_REATTENDED) {
				if (bMirandaOrWindows == ACTIVE_WINDOWS && !bEmulateKeypresses) {
					LASTINPUTINFO ii = { sizeof(ii) };
					GetLastInputInfo(&ii);
					dwLastInput = ii.dwTime;
				}
				if (dwLastInput > dwEventStarted)
					break;
			}
			if ((bFlashUntil & UNTIL_EVENTSOPEN) && !checkUnopenEvents())
				break;
			if ((bFlashUntil & UNTIL_CONDITIONS) && (!checkNotifyOptions() || !checkGlobalStatus() || !checkGlobalXstatus()))
				break;

			data = getBlinkingLeds();
			ToggleKeyboardLights((BYTE)(data | unchangedLeds));

			// Wait for exit event
			if (WaitForSingleObject(hExitEvent, nWaitDelay) == WAIT_OBJECT_0)
				return;
		}
		RestoreLEDState();

		setFlashingSequence();
		bReminderDisabled = FALSE;

		// Wait for new event
		HANDLE Objects[2];
		Objects[0] = hFlashEvent;
		Objects[1] = hExitEvent;
		if (WaitForMultipleObjects(2, Objects, FALSE, INFINITE) == WAIT_OBJECT_0 + 1)
			return;

		bEvent = TRUE;
		bReminderDisabled = TRUE;
		dwEventStarted = GetTickCount();
		// Wait StartDelay seconds
		if (wStartDelay > 0)
			Sleep(wStartDelay * 1000);
		dwFlashStarted = GetTickCount();
	}
}
Ejemplo n.º 2
0
void SysEventMonitor::onTimeout() {
#ifdef _WIN32
    LASTINPUTINFO li;
    li.cbSize = sizeof(LASTINPUTINFO);
    if (!GetLastInputInfo(&li)) {
        qDebug() << "SysEventMonitor::something wrong with GetLastInputInfo()";
    }

    DWORD timeDiffMs = GetTickCount() - li.dwTime;
    DWORD inactThreshMs = settings_.value(SettingInactivityThreshold, SettingInactivityThresholdDefVal).toUInt();
    Q_ASSERT(inactThreshMs > 0);

    if (timeDiffMs < inactThreshMs) {
        if (!activeState_) {
            activeState_ = true;
            Logger::logEvent(Logger::UserStateActive);
            emit userStateActive();
        }
    } else {
        if (activeState_) {
            activeState_ = false;
            Logger::logEvent(Logger::UserStateInactive);
            emit userStateInactive();
        }
    }
#endif
}
Ejemplo n.º 3
0
/**   Platform specific routine for checking the idle state

    * @return bool
*/
bool WindowsSystemIdle::CheckIdle(void)
{
    LASTINPUTINFO inputInfo  = {0};
    DWORD         dwTicksNow = 0;

    inputInfo.cbSize = sizeof(inputInfo);

    if (GetLastInputInfo(&inputInfo) == FALSE)
    {
        return false;
    }

    dwTicksNow = GetTickCount();

    inputInfo.dwTime /= 1000;
    dwTicksNow /= 1000;

    dwTicksNow -= inputInfo.dwTime;

    int nInterval = 0;

    m_pConfiguration->getInterval(nInterval);

    return (dwTicksNow >= nInterval);
}
Ejemplo n.º 4
0
void OnTimer(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    if (g_enumWindowState == Hidden)
    {
        static DWORD dwLastInput = 0;

        LASTINPUTINFO stInfo = { sizeof(stInfo) };
        GetLastInputInfo(&stInfo);

        // Update the time of last input event
        if (stInfo.dwTime != dwLastInput)
            dwLastInput = stInfo.dwTime;

        // Display window when it's idle for one minute
        DWORD dwTime = GetTickCount();
        if (dwTime - dwLastInput > g_uTimeout * 1000 && g_bAutoLock)
        {
            Lock(hWnd);
        }
    }
    else
    {
        SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
    }
}
Ejemplo n.º 5
0
DWORD GetUserIdleTime()
{
    DWORD dwTickCount=GetTickCount();
    LASTINPUTINFO liiInfo;
    liiInfo.cbSize=sizeof(LASTINPUTINFO);
    GetLastInputInfo(&liiInfo);
    return (dwTickCount-liiInfo.dwTime)/1000;
}
Ejemplo n.º 6
0
uint32_t Platform::getIdleTime()
{
    LASTINPUTINFO info = {0, 0};
    info.cbSize = sizeof(info);
    if (GetLastInputInfo(&info))
        return GetTickCount() - info.dwTime;
    return 0;
}
Ejemplo n.º 7
0
bool isComputerIdle(int idle_secs)
{
    LASTINPUTINFO info;
    info.cbSize = sizeof(LASTINPUTINFO);
    if( GetLastInputInfo(&info))
         return (::GetTickCount() - info.dwTime) / 1000 >= (UINT)idle_secs;
    else
        return false;
}
int WindowsIdleQuerier::getIdleTimeSeconds() {
	LASTINPUTINFO info;
	info.cbSize = sizeof(info);
	if (GetLastInputInfo(&info)) {
		return (GetTickCount() - info.dwTime) / 1000;
	}
	else {
		return 0;
	}
}
Ejemplo n.º 9
0
void RelaxTimer::ProcessWorkStatus()
{
    LASTINPUTINFO lpi;
    lpi.cbSize = sizeof(lpi);
    GetLastInputInfo(&lpi);

    // 如果使用了全屏自动暂停,每10秒钟检查是否在全屏模式
    if (m_bEnableFullScreenPause == TRUE)
    {
        CTime timeAutoSave = CTime::GetCurrentTime();
        if (timeAutoSave.GetSecond() % 10 == 0)
        {
            if (FullscreenModeDectect())
            {
                Work2AutoPause(AUTO_PAUSE_FULLSCREEN);
                return;
            }
        }
    }

    // 如果使用了自动暂停状态转换,则处理鼠标键盘未输入的自动状态转换
    if (m_bEnableAutoPause == TRUE)
    {
        if (::GetTickCount()-lpi.dwTime >= m_nAutoPauseThreshold * 1000)
        {
            Work2AutoPause(AUTO_PAUSE_IDLE);
            return;
        }
    }
    // 如果使用了自动复位状态转换,则处理鼠标键盘未输入的自动状态转换
    if (m_bEnableAutoReset == TRUE)
    {
        // 如果长时间没有输入,则转入自动复位态
        if (::GetTickCount() - lpi.dwTime >= m_nAutoResetThreshold * 1000)
        {
            Work2AutoReset();
            return;
        }
    }

    IncLS();
    if (m_nLapsedSeconds >= m_nWorkDuration)    
    {// 工作状态结束,准备进入休息状态
        if (m_bEnableLongRelax && m_nShortRelaxedTimes >= m_nLongRelaxFrequency)
        {// 如果启用了长休息,且短休息次数大于设定值,则开始长休息
            Work2LongRelax();
        }
        else
        {// 否则直接开始短休息
            Work2ShortRelax();
        }
    }
}
void SweetDisplayStandby::timerTick()
{
    LASTINPUTINFO LastInput = {};
    LastInput.cbSize = sizeof(LastInput);
    GetLastInputInfo(&LastInput);
    int idleTime = (GetTickCount() - LastInput.dwTime) / 1000;

    if (idleTime>displayOffTime || forceDisplayTurnOff)
    {
        if (!displayWasTurnedOff)
        {
            EXECUTION_STATE cap;
            NTSTATUS status;
            status = CallNtPowerInformation(SystemExecutionState, NULL, 0, &cap, sizeof(cap));
            if (!(cap & ES_DISPLAY_REQUIRED))
            {
                addToQueue("turnOff");
                displayWasTurnedOff = true;
                //lastInputTime = LastInput.dwTime;
            }
        }
        forceDisplayTurnOff = false;
    }
    else if (idleTime>displayDimTime && enableBrighnessManagement)
    {
        if (!displayWasDimmed)
        {
            EXECUTION_STATE cap;
            NTSTATUS status;
            status = CallNtPowerInformation(SystemExecutionState, NULL, 0, &cap, sizeof(cap));
            if (!(cap & ES_DISPLAY_REQUIRED))
            {
                addToQueue("dim");
                displayWasDimmed = true;
            }
        }
    }
    else if (LastInput.dwTime > lastInputTime)
    {
        if (displayWasTurnedOff)
        {
            addToQueue("turnOn");
            displayWasTurnedOff = false;
        }
        if (displayWasDimmed)
        {
            addToQueue("illuminate");
            displayWasDimmed = false;
        }
        lastInputTime = LastInput.dwTime + 1000; //Give async function more time
    }
}
Ejemplo n.º 11
0
int main()
{
	LASTINPUTINFO lpi;
	lpi.cbSize = sizeof(lpi);

	while (1)
	{
		int ret = GetLastInputInfo(&lpi);
		printf("%d, idle for %d s.\n", ret, (::GetTickCount()-lpi.dwTime)/1000);
		Sleep(500);
	}
	return 0;
}
JNIEXPORT jlong JNICALL
Java_net_java_sip_communicator_impl_sysactivity_SystemActivityNotifications_getLastInput
    (JNIEnv* env, jclass clazz)
{
    (void) env;
    (void) clazz;

    LASTINPUTINFO lii;

    lii.cbSize = sizeof(LASTINPUTINFO);
    lii.dwTime = 0;
    return GetLastInputInfo(&lii) ? (GetTickCount() - lii.dwTime) : -1;
}
Ejemplo n.º 13
0
static bool IsUserIdle()
{
	DWORD dwTick;
	if (g_wMaskAdv & OPT_HIDEIFMIRIDLE) {
		CallService(MS_SYSTEM_GETIDLE, 0, (LPARAM)&dwTick);
		return GetTickCount() - dwTick > (minutes * 60 * 1000);
	}

	LASTINPUTINFO ii = { sizeof(ii) };
	if (GetLastInputInfo(&ii))
		return GetTickCount() - ii.dwTime > (minutes * 60 * 1000);

	return FALSE;
}
Ejemplo n.º 14
0
static int IdleObject_IsUserIdle(IdleObject * obj)
{
	DWORD dwTick;
	if (IdleObject_GetMethod(obj)) {
		CallService(MS_SYSTEM_GETIDLE, 0, (LPARAM)&dwTick);
		return GetTickCount() - dwTick > (obj->minutes * 60 * 1000);
	}

	LASTINPUTINFO ii = { sizeof(ii) };
	if ( GetLastInputInfo(&ii))
		return GetTickCount() - ii.dwTime > (obj->minutes * 60 * 1000);

	return FALSE;
}
/*
 * Class:     net_java_sip_communicator_impl_sysactivity_SystemActivityNotifications
 * Method:    getLastInput
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_net_java_sip_communicator_impl_sysactivity_SystemActivityNotifications_getLastInput
(JNIEnv* jniEnv, jclass clazz)
{
    DWORD result = 0;

    LASTINPUTINFO lii;
    memset(&lii, 0, sizeof(lii));
    lii.cbSize = sizeof(LASTINPUTINFO);
    if (GetLastInputInfo(&lii))
    {
        return GetTickCount() - lii.dwTime;
    }

    return -1;
}
Ejemplo n.º 16
0
void RelaxTimer::ProcessAutoResetStatus()
{
    LASTINPUTINFO lpi;
    lpi.cbSize = sizeof(lpi);
    GetLastInputInfo(&lpi);

    if (m_bEnableAutoReset == TRUE)
    {
        // 如果发现有输入,则转入工作态
        if (::GetTickCount() - lpi.dwTime < m_nAutoResetThreshold * 1000)
        {
            AutoReset2Work();
            return;
        }
    }
}
Ejemplo n.º 17
0
void WindowsIdleDetector::timeout() {
    LASTINPUTINFO lif;
    lif.cbSize = sizeof( lif );
    const bool ret = GetLastInputInfo( &lif );
    if ( !ret ) {
        qWarning() << "Idle detection: GetLastInputInfo failed.";
        return;
    }

    const qint64 dwTime = static_cast<qint64>( lif.dwTime );
    const qint64 ctk = static_cast<qint64>( GetTickCount() );
    const int idleSecs = ( ctk - dwTime ) / 1000;
    if ( idleSecs >= idlenessDuration() )
        maybeIdle( IdlePeriod(QDateTime::currentDateTime().addSecs( -idleSecs ),
                              QDateTime::currentDateTime() ) );
}
Ejemplo n.º 18
0
long idleTime() {
    long idlesecs;
#ifdef LINUX
    bool _idleDetectionPossible;
    XScreenSaverInfo *_mit_info;

    int event_base, error_base;
    if(XScreenSaverQueryExtension(QX11Info::display(), &event_base, &error_base))
        _idleDetectionPossible = true;
    else
        _idleDetectionPossible = false;
    _mit_info = XScreenSaverAllocInfo();

    XScreenSaverQueryInfo(QX11Info::display(), QX11Info::appRootWindow(), _mit_info);

    idlesecs = (_mit_info->idle/1000);

#endif
#ifdef WINDOWS

    LASTINPUTINFO lif;
    lif.cbSize = sizeof(LASTINPUTINFO);
    GetLastInputInfo(&lif);
    DWORD tickCount = GetTickCount();
    idlesecs = (tickCount - lif.dwTime) / 1000;

#endif
#ifdef MAC
    idlesecs = -1;//int64_t
    io_iterator_t iter = 0;
    if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOHIDSystem"), &iter) == KERN_SUCCESS) {
        io_registry_entry_t entry = IOIteratorNext(iter);
        if (entry) {
            CFMutableDictionaryRef dict = NULL;
            if (IORegistryEntryCreateCFProperties(entry, &dict, kCFAllocatorDefault, 0) == KERN_SUCCESS) {
                CFNumberRef obj = (CFNumberRef)CFDictionaryGetValue(dict, CFSTR("HIDIdleTime"));
                if (obj) {
                    int64_t nanoseconds = 0;
                    if (CFNumberGetValue(obj, kCFNumberSInt64Type, &nanoseconds)) {
                        idlesecs = (nanoseconds >> 30); // Divide by 10^9 to convert from nanoseconds to seconds.
                    }
                }
                CFRelease(dict);
            }
Ejemplo n.º 19
0
void InactivityPoller::checkUp()
{
	LASTINPUTINFO lp;
    lp.cbSize = sizeof(lp);
    GetLastInputInfo(&lp);
    int cur_t=(GetTickCount()-lp.dwTime);
	if (cur_t >= timeout_){
		if (isActive_){
			isActive_=false;
			Notify();
		}
	}
	else {
		if(!isActive_){
			isActive_=true;
			Notify();
		}
	}
}
Ejemplo n.º 20
0
void NotifyWindow::checkLastInput() {
#ifdef Q_OS_WIN
	LASTINPUTINFO lii;
	lii.cbSize = sizeof(LASTINPUTINFO);
	BOOL res = GetLastInputInfo(&lii);
	if (!res || lii.dwTime >= started) {
		hideTimer.start(st::notifyWaitLongHide);
	} else {
		inputTimer.start(300);
	}
#else
    // TODO
	if (true) {
		hideTimer.start(st::notifyWaitLongHide);
	} else {
		inputTimer.start(300);
	}
#endif
}
Ejemplo n.º 21
0
void RelaxTimer::ProcessAutoPauseStatus()
{
    LASTINPUTINFO lpi;
    lpi.cbSize = sizeof(lpi);
    GetLastInputInfo(&lpi);

    if (m_eAutoPauseType == AUTO_PAUSE_FULLSCREEN)
    {
        if (FullscreenModeDectect() == FALSE)
        {// 如果不在全屏模式,则允许进入工作状态,且继续进行idle状态检测
            AutoPause2Work();
        }
        else
        {// 如果仍然处于是全屏状态,则不允许进行后续的idle状态检测
            return;
        }
    }
    
    if (m_bEnableAutoPause == TRUE)
    {
        // 如果发现有输入,则转入工作态
        if (::GetTickCount() - lpi.dwTime < m_nAutoPauseThreshold * 1000)
        {
            AutoPause2Work();
            return;
        }
    }
    if (m_bEnableAutoReset == TRUE)
    {
        // 如果长时间没有输入,则转入自动复位态
        if (::GetTickCount() - lpi.dwTime >= m_nAutoResetThreshold * 1000)
        {
            AutoPause2AutoReset();
            return;
        }
    }
}
Ejemplo n.º 22
0
LRESULT
CMainWindow::OnTimer(WPARAM wParam)
{
    LASTINPUTINFO lii;
    ULONGLONG TickCount;

    if (wParam == IDT_TIMER)
    {
        ZeroMemory(&lii, sizeof(LASTINPUTINFO));
        lii.cbSize = sizeof(LASTINPUTINFO);

        if (GetLastInputInfo(&lii))
        {
            TickCount = GetTickCount64();

            if (TickCount  > lii.dwTime + SLEEP_TIME)
            {
                TurnDisplayOff();
            }
        }
    }

    return 0;
}
Ejemplo n.º 23
0
static BOOL
check_for_active_sessions(void)
{
	WTS_SESSION_INFO *session_info;
	DWORD session_info_count;
	BOOL rv;
	BOOL found_active_session = FALSE;

	rv = WTSEnumerateSessions(
			WTS_CURRENT_SERVER_HANDLE,
			0, /* Reserved */
			1, /* Version */
			&session_info,
			&session_info_count);
	if (!rv)
	{
		logger_printf(TEXT("WTSEnumerateSessions: error"));
		return FALSE;
	}

	if (session_info_count > 0)
	{
		size_t i;
		for (i = 0; i < session_info_count; i++)
		{
			logger_printf(TEXT("session %d \"%s\" is %d"),
				session_info[i].SessionId,
				session_info[i].pWinStationName,
				session_info[i].State);

			{
				TCHAR *pBuffer = NULL;
				DWORD bytesReturned;
				if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, session_info[i].SessionId,
						WTSUserName, &pBuffer, &bytesReturned))
				{
					logger_printf(TEXT("  username: %s"), pBuffer);
					if (_tcscmp(TEXT("Student-PAC"), pBuffer) == 0)
					{
						logger_printf(TEXT("  this username is EXEMPT"));
					}
					else if (session_info[i].State == WTSActive
						&& _tcscmp(TEXT("Console"), session_info[i].pWinStationName) == 0
						&& _tcslen(pBuffer) > 0)
					{
						logger_printf(TEXT("  this session is active"));
						found_active_session = TRUE;
					}
					WTSFreeMemory(pBuffer);
					pBuffer = NULL;
				}
			}

		}
	}
	else
	{
		logger_printf(TEXT("no sessions found"));
	}

	WTSFreeMemory(session_info);

	{
		LASTINPUTINFO lii = { sizeof(LASTINPUTINFO) };
		if (GetLastInputInfo(&lii))
		{
			size_t elapsed = GetTickCount() - lii.dwTime;
			logger_printf(TEXT("Note: %d seconds since last input"), elapsed / 1000);
		//	if (elapsed / 1000 < 300 && lii.dwTime / 1000 > 300)
		//	{
		//		return TRUE;
		//	}
		}
	}

	logger_printf(TEXT("found active session == %s"),
			found_active_session ? TEXT("true") : TEXT("false"));
	return found_active_session;
}
Ejemplo n.º 24
0
void 
PollActivity()
{
#ifdef WIN32
	LASTINPUTINFO lii;
	static POINT previous_pos = { 0, 0 }; 
	static DWORD previous_input_tick = 0;

	lii.cbSize = sizeof(LASTINPUTINFO);
	lii.dwTime = 0;

	if ( !GetLastInputInfo(&lii) ) {
		dprintf(D_ALWAYS, "PollActivity: GetLastInputInfo()"
			" failed with err=%d\n", GetLastError());
	}
	else
	{

		//Check if there has been new keyboard input since the last check.
		if(lii.dwTime > previous_input_tick)
		{
			previous_input_tick = lii.dwTime;
			update_startd();
		}

		return;
	}

	//If no change to keyboard input, check if mouse has been moved.
	CURSORINFO cursor_inf;
	cursor_inf.cbSize = sizeof(CURSORINFO);
	if (!GetCursorInfo(&cursor_inf))
	{
		dprintf(D_ALWAYS,"GetCursorInfo() failed (err=%li)\n",
		GetLastError());
	}
	else
	{
		if ((cursor_inf.ptScreenPos.x != previous_pos.x) || 
			(cursor_inf.ptScreenPos.y != previous_pos.y))
		{
			// the mouse has moved!
			// stash new position
			previous_pos.x = cursor_inf.ptScreenPos.x; 
			previous_pos.y = cursor_inf.ptScreenPos.y;
			previous_input_tick = GetTickCount();
			update_startd();
		}
	}

	return;

#else
    if(xinter != NULL)
    {
	if(xinter->CheckActivity())
	{
	    update_startd();
	}
    }
#endif
}
Ejemplo n.º 25
0
static
DWORD
WINAPI
ScreenSaverThreadMain(
    IN LPVOID lpParameter)
{
    PWLSESSION Session = (PWLSESSION)lpParameter;
    HANDLE HandleArray[3];
#ifdef USE_GETLASTINPUTINFO
    LASTINPUTINFO lastInputInfo;
#else
    DWORD LastActivity;
#endif
    DWORD TimeToWait;
    DWORD Timeout; /* Timeout before screen saver starts, in milliseconds */
    DWORD ret;

    if (!ImpersonateLoggedOnUser(Session->UserToken))
    {
        ERR("ImpersonateLoggedOnUser() failed with error %lu\n", GetLastError());
        return 0;
    }

    Session->hUserActivity = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!Session->hUserActivity)
    {
        ERR("WL: Unable to create event (error %lu)\n", GetLastError());
        goto cleanup;
    }

    Session->hEndOfScreenSaver = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!Session->hEndOfScreenSaver)
    {
        ERR("WL: Unable to create event (error %lu)\n", GetLastError());
        goto cleanup;
    }

    HandleArray[0] = Session->hEndOfScreenSaverThread;
    HandleArray[1] = Session->hScreenSaverParametersChanged;
    HandleArray[2] = Session->hEndOfScreenSaver;

    LoadScreenSaverParameters(&Timeout);

#ifndef USE_GETLASTINPUTINFO
    InterlockedExchange((LONG*)&Session->LastActivity, GetTickCount());
#else
    lastInputInfo.cbSize = sizeof(LASTINPUTINFO);
#endif
    for (;;)
    {
        /* See the time of last activity and calculate a timeout */
#ifndef USE_GETLASTINPUTINFO
        LastActivity = InterlockedCompareExchange((LONG*)&Session->LastActivity, 0, 0);
        TimeToWait = Timeout - (GetTickCount() - LastActivity);
#else
        if (GetLastInputInfo(&lastInputInfo))
            TimeToWait = Timeout - (GetTickCount() - lastInputInfo.dwTime);
        else
        {
            WARN("GetLastInputInfo() failed with error %lu\n", GetLastError());
            TimeToWait = 10; /* Try again in 10 ms */
        }
#endif

        if (TimeToWait > Timeout)
        {
            /* GetTickCount() got back to 0 */
            TimeToWait = Timeout;
        }

        /* Wait for the timeout, or the end of this thread */
        ret = WaitForMultipleObjects(2, HandleArray, FALSE, TimeToWait);
        if (ret == WAIT_OBJECT_0)
            break;
        else if (ret == WAIT_OBJECT_0 + 1)
            LoadScreenSaverParameters(&Timeout);

        /* Check if we didn't had recent activity */
#ifndef USE_GETLASTINPUTINFO
        LastActivity = InterlockedCompareExchange((LONG*)&Session->LastActivity, 0, 0);
        if (LastActivity + Timeout > GetTickCount())
            continue;
#else
        if (!GetLastInputInfo(&lastInputInfo))
        {
            WARN("GetLastInputInfo() failed with error %lu\n", GetLastError());
            continue;
        }

        if (lastInputInfo.dwTime + Timeout > GetTickCount())
            continue;
#endif

        /* Run screen saver */
        PostMessageW(Session->SASWindow, WLX_WM_SAS, WLX_SAS_TYPE_SCRNSVR_TIMEOUT, 0);

        /* Wait for the end of this thread or of the screen saver */
        ret = WaitForMultipleObjects(3, HandleArray, FALSE, INFINITE);
        if (ret == WAIT_OBJECT_0)
            break;
        else if (ret == WAIT_OBJECT_0 + 1)
            LoadScreenSaverParameters(&Timeout);
        else if (ret == WAIT_OBJECT_0 + 2)
            SystemParametersInfoW(SPI_SETSCREENSAVERRUNNING, FALSE, NULL, 0);
    }

cleanup:
    RevertToSelf();
    if (Session->hUserActivity)
        CloseHandle(Session->hUserActivity);

    if (Session->hEndOfScreenSaver)
        CloseHandle(Session->hEndOfScreenSaver);

#ifndef USE_GETLASTINPUTINFO
    if (Session->KeyboardHook)
        UnhookWindowsHookEx(Session->KeyboardHook);

    if (Session->MouseHook)
        UnhookWindowsHookEx(Session->MouseHook);
#endif

    CloseHandle(Session->hEndOfScreenSaverThread);
    CloseHandle(Session->hScreenSaverParametersChanged);
    return 0;
}
Ejemplo n.º 26
0
int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 2)
	{
		MessageBox(NULL, "Must be run with at least one argument. (See README)", "KBTimer: Error", MB_OK);
		return 0;
	}

	LPSTR keyboardHandle = argv[1];
	int idle_min_threshold = (argc >= 3) ? strtol(argv[2], NULL, NULL) : 15;
	int normal_brightness_level = (argc >= 4) ? strtol(argv[3], NULL, NULL) : 1;
	int idle_brightness_level = (argc >= 5) ? strtol(argv[4], NULL, NULL) : 0;

	bool system_is_idle = false;
	int idle_ms_threshold = 1000*60*idle_min_threshold;

	FreeConsole();
	
	HWND kbHWND = FindWindow(NULL, keyboardHandle);

	while (kbHWND == NULL && GetTickCount64() < 2*60*1000)
	{
		//On first boot, it is possible KBTimer will run before keyboard driver is ready. So, keep trying for 2 minutes before giving up.
		kbHWND = FindWindow(NULL, keyboardHandle);
	}

	
	if (kbHWND != NULL)
	{
		LASTINPUTINFO lastInput;
		lastInput.cbSize=sizeof(LASTINPUTINFO);

		for (;;)
		{
			if(system_is_idle)
			{
				Sleep(500);
				if (GetLastInputInfo(&lastInput))
				{
					if (GetTickCount64() - lastInput.dwTime < 1000)
					{
						setBrightness(kbHWND, normal_brightness_level);
						system_is_idle = false;
					}
				}
			}
			else
			{
				Sleep(60000);
				if (GetLastInputInfo(&lastInput))
				{
					if (GetTickCount64() - lastInput.dwTime > idle_ms_threshold)
					{
						setBrightness(kbHWND, idle_brightness_level);
						system_is_idle = true;
					}
				}
			}
		}

	}
	else
	{
		MessageBox(NULL, "Keyboard not detected", "KBTimer: Error", MB_OK);
	}


	return 0;
}