使用WinAPI处理用户注销问题

时间:2018-12-24 21:38:07

标签: c++ winapi

我正在做一个个人项目,以为我的DIY流光溢彩设置(Github repo)供电。总而言之,该程序始终运行一系列命令,并将其发送到外部Arduino板,然后该板将处理所有内容。如果用户在哪里锁定他的会话甚至注销,则应向董事会发送最终消息。我的问题是我无法正确处理WM_WTSSESSION_CHANGE消息。

任何帮助都可以帮助您。 Ambilight::pause应该只暂时停止执行,而Ambilight::stop应该完全结束一切。我真的不知道应该在哪里调用方法Ambilight::stop,因为这是我的第一个使用WinAPI的项目。我的算法在单独的线程中运行;我认为这可能是问题所在。这是用于处理所有内容的简化代码:

main.cpp

// ... global initializations

LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    // ... other messages handling

    case WM_WTSSESSION_CHANGE:
        // this case doesn't seem to work properly
        switch (wParam)
        {
        case WTS_SESSION_UNLOCK:
            ambilight.start();
            break;

        case WTS_SESSION_LOCK:
            ambilight.pause();
            break;

        case WTS_SESSION_LOGOFF:
            ambilight.stop();
            break;
        }
        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    }

    return DefWindowProc(hwnd, message, wParam, lParam);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    // ... hWnd Creation

    WTSRegisterSessionNotification(hWnd, NOTIFY_FOR_THIS_SESSION);

    ambilight.start();

    MSG message;
    while (GetMessage(&message, NULL, 0, 0))
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    ambilight.stop();

    return (int)message.wParam;
}

Ambilight.cpp

#include "Ambilight.h"

Ambilight::Ambilight(const Options & options)
    : isPaused(true),
    isStopped(false),
    thread(&Ambilight::exec, this, options)
{ }

Ambilight::~Ambilight()
{
    this->stop();
}

void Ambilight::start()
{
    this->isPaused = false;
}

void Ambilight::pause()
{
    this->isPaused = true;
}

void Ambilight::stop()
{
    this->pause();
    this->isStopped = true;

    if (this->thread.joinable())
    {
        this->thread.join();
    }
}

void Ambilight::exec(const Options & options) const
{
    // .. action initialization

    bool hasFaded = false;
    while (!this->isStopped)
    {
        while (!this->isPaused)
        {
            // ... recurring action

            hasFaded = false;
        }

        if (!hasFaded)
        {
            // ... action that is supposed to be execute when user logs off

            hasFaded = true;
        }
    }

}

0 个答案:

没有答案