使用 Qt 将应用程序固定到任务栏的控制路径

Control path to pinned application to taskbar with Qt

如何使用 Qt 控制将应用程序固定到任务栏的路径

因为我自己一直在努力寻找一种方法来自定义固定到任务栏的应用程序的程序路径,所以我想post在这里我的与 Qt 相关的解决方案。

问题是,当固定主程序时,我 link 是一组程序(starter/updater、主程序)中的启动程序。

EventFilterPinnable.h

#pragma once

#include <QAbstractNativeEventFilter>

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <propsys.h>
#include <propkey.h>
#include <propvarutil.h>

HRESULT PropertyStoreSetStringValue(IPropertyStore* propertyStore, REFPROPERTYKEY pkey, PCWSTR value)
{
    PROPVARIANT propVariant;
    HRESULT hr = InitPropVariantFromString(value, &propVariant);
    if(SUCCEEDED(hr))
    {
        hr = propertyStore->SetValue(pkey, propVariant);
        PropVariantClear(&propVariant);
    }
    return hr;
}

HRESULT MakeWindowPinnable(HWND hwnd, PCWSTR userModelId, PCWSTR relaunchCommand, PCWSTR relaunchDisplayName, PCWSTR relaunchIcon = NULL)
{
    IPropertyStore* propertyStore;
    HRESULT hr = SHGetPropertyStoreForWindow(hwnd, IID_PPV_ARGS(&propertyStore));
    if(SUCCEEDED(hr))
    {
        PropertyStoreSetStringValue(propertyStore, PKEY_AppUserModel_ID, userModelId);
        PropertyStoreSetStringValue(propertyStore, PKEY_AppUserModel_RelaunchCommand, relaunchCommand);
        PropertyStoreSetStringValue(propertyStore, PKEY_AppUserModel_RelaunchDisplayNameResource, relaunchDisplayName);

        if(relaunchIcon != NULL)
        {
            PropertyStoreSetStringValue(propertyStore, PKEY_AppUserModel_RelaunchIconResource, relaunchIcon);
        }

        propertyStore->Release();
    }
    return hr;
}

void OnCreate(HWND hwnd)
{
    std::wstring sAppId = L"unique.app.id";
    std::wstring sAppRelaunchCommand = L"\"C:\Program Files\Path with spaces\Starter.exe\" -a argument1";
    std::wstring sAppRelaunchDisplayName = L"Name of progam";
    std::wstring sAppRelaunchIcon = L"\"C:\Program Files\Path with spaces\Icon.ico\"";

    MakeWindowPinnable(hwnd, sAppId.c_str(), sAppRelaunchCommand.c_str(), sAppRelaunchDisplayName.c_str(), sAppRelaunchIcon.c_str());
}


class EventFilterPinnable : public QAbstractNativeEventFilter
{
public:
    EventFilterPinnable() {}

    bool nativeEventFilter(const QByteArray& eventType, void* message, long* /*res*/) override
    {
        if(eventType == "windows_generic_MSG") {
            MSG* msg = static_cast<MSG*>(message);
            HWND hwnd = msg->hwnd;

            if (msg->message==WM_CREATE)
            {
                OnCreate(hwnd);
            }
        }
        return false;
    }
};

在main.cpp中只需添加

QApplication app(argc, argv);    
app.installNativeEventFilter(new EventFilterPinnable());
....
app.exec();