在windows上使用Qt5(从WId)获取HWND

Get HWND on windows with Qt5 (from WId)

本文关键字:WId 获取 HWND Qt5 windows      更新时间:2023-10-16

我正在尝试将Qt4应用程序转换为Qt5。我唯一弄不明白的是如何获得Widget的HWND。该程序使用EcWin7在win7 +上的任务栏图标上显示进度,但需要一个HWND。在将Q_WS_WIN更改为Q_OS_WIN之后,库本身似乎可以很好地编译。在Windows的Qt4中,WId只是HWND的类型定义,所以这不是问题。在Qt5中,情况不再是这样了。我发现了一些邮件列表的帖子,可以给出一个线索,但似乎QPlatformNativeInterface不再是Qt5的公共API的一部分。

程序调用EcWin7.init(this->winId());我需要一些方法将这个ID转换为HWND ID或其他方法来获得这个

在Qt5中winEventnativeEvent取代:

bool winEvent(MSG* pMsg, long* result)
现在

bool nativeEvent(const QByteArray & eventType, void * message, long *result)

EcWin7::winEvent中,你必须将void转换为MSG:

bool EcWin7::winEvent(void * message, long * result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);
    if (msg->message == mTaskbarMessageId)
    {
      ...

我能够让应用程序工作!只是替换:

 mWindowId = wid;

 mWindowId = (HWND)wid;
#include <QtGui/5.0.0/QtGui/qpa/qplatformnativeinterface.h>
static QWindow* windowForWidget(const QWidget* widget) 
{
    QWindow* window = widget->windowHandle();
    if (window)
        return window;
    const QWidget* nativeParent = widget->nativeParentWidget();
    if (nativeParent) 
        return nativeParent->windowHandle();
    return 0; 
}
HWND getHWNDForWidget(const QWidget* widget)
{
    QWindow* window = ::windowForWidget(widget);
    if (window && window->handle())
    {
        QPlatformNativeInterface* interface = QGuiApplication::platformNativeInterface();
        return static_cast<HWND>(interface->nativeResourceForWindow(QByteArrayLiteral("handle"), window));
    }
    return 0; 
}

你可以试试:

(HWND)QWidget::winId();

试试这个函数:QWindowsNativeInterface::nativeResourceForWindow

winId()在Qt 5.1上为我工作至少当我使用

时它有相同的值
bool Widget::nativeEvent(const QByteArray & eventType, void * message, long * result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);
    qDebug() << msg->hwnd;
    return false;
}

qDebug() << winId();