在第三方窗口上显示QT小部件(在Windows中)



这不是我以前尝试过的东西,我是一个完全的新手,喜欢HWND,钩子等。

基本上,我想在第三方应用程序的窗口上显示/覆盖QT小部件(我无法控制,我只知道非常基本的信息,如窗口标题/标题及其类名),我完全不知道如何做到这一点。我还希望QT小部件保持在第三方应用程序窗口的相对位置,即使该窗口在屏幕上移动。

WinAPI部件

  1. 使用FindWindow函数获取目标窗口HWND
  2. 使用GetWindowRect获取窗口的当前位置

Qt部分
  1. 让你的顶级QWidgetQMainWindow无框,并使其保持在顶部使用窗口标志Qt::FramelessWindowHintQt::WindowStaysOnTopHint
  2. 使用属性Qt::WA_TranslucentBackground使其透明。
  3. 设置QTimer定期请求窗口矩形,并调整小部件位置。

示例代码(已测试)

添加标题:

private:
  HWND target_window;
private slots:
  void update_pos();
源:

#include "Windows.h"
#include <QDebug>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
  setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
  setAttribute(Qt::WA_TranslucentBackground);
  // example of target window class: "Notepad++"
  target_window = FindWindowA("Notepad++", 0); 
  if (!target_window) {
    qDebug() << "window not found";
    return;
  }
  QTimer* timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(update_pos()));
  timer->start(50); // update interval in milliseconds 
}
MainWindow::~MainWindow() {
  delete ui;
}
void MainWindow::update_pos() {
  RECT rect;
  if (GetWindowRect(target_window, &rect)) {
    setGeometry(rect.left, rect.top, rect.right - rect.left, 
                rect.bottom - rect.top);
  } else {
    //maybe window was closed
    qDebug() << "GetWindowRect failed";
    QApplication::quit();
  }
}

最新更新