使用Qt5获取Windows上的HWND(从WId)

35

我试图将一个Qt4应用程序转换为Qt5。

唯一我弄不清楚的是如何获取小部件的HWND

该程序使用EcWin7在Win 7+上显示任务栏图标上的进度,但需要一个HWND。该库本身在更改Q_WS_WINQ_OS_WIN后似乎编译正常)。 在Windows上,WId在Qt4中只是一个HWND的typedef,所以这不是问题。 在Qt5中不再是这样。 我找到了一些邮件列表发布,可能会给出一些线索,但似乎QPlatformNativeInterface不再是Qt5的公共API的一部分。

程序调用EcWin7.init(this->winId());,我需要某种方法将此ID转换为HWND ID或其他获取方法。


3
好的,很奇怪。QWidget::winId()在Windows上应该返回HWND,就像在Qt4中一样。 - Maciej
5个回答

26
在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;

很不幸,存在许多漏洞。并非所有事件都传递给真正的小部件,其中很多事件会传递到顶层小部件。 - Dmitry Sazonov

11
#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; 
}

3
证实,并提供更多详细信息如何编译此代码:http://lists.qt-project.org/pipermail/interest/2013-June/007650.html - David Burson

3

您可以尝试以下方法:

(HWND)QWidget::winId();

2

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

2

尝试使用此函数:QWindowsNativeInterface::nativeResourceForWindow


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接