c++ - 在第三方窗口上显示/覆盖 QT 小部件(在 Windows 中)

标签 c++ qt winapi overlay hook

这不是我以前尝试过的东西,我对 HWND、hooking 等完全是个新手。

基本上,我想在第 3 方应用程序的窗口顶部显示/覆盖 QT 小部件(我无法控制,我只知道非常基本的信息,如窗口标题/标题及其类名)和我完全不知道人们会怎么做。我还希望 QT 小部件保留在与第 3 方应用程序窗口相对的位置,即使该窗口在屏幕上移动也是如此。

最佳答案

WinAPI部分

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

Qt部分

  1. 使您的顶级QWidgetQMainWindow 无框架,并使用window flags 使其保持在顶部Qt::FramelessWindowHintQt::WindowStaysOnTopHint
  2. 使用 attribute 使其透明Qt::WA_TranslucentBackground
  3. 设置一个 QTimer 来定期请求窗口 rect 并调整小部件的位置。

示例代码(已测试)

在标题中添加:

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

关于c++ - 在第三方窗口上显示/覆盖 QT 小部件(在 Windows 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929090/

相关文章:

windows - 如何通过程序检查应用是否发出某种声音?

C++ - RtMidi 不向输出端口发送任何内容

c++ - 老程序员需要STL秘籍

multithreading - Qt + OpenCV 使用 std::thread 播放视频

qt - 在 C++ 中创建 QML 元素?

c++ - EnumResTypeProc 空白 LPTSTR 参数

c++ - `std::filesystem::path::operator/(/*args*/)` 没有按预期工作

c++ - 如何将 std::vector<uint8_t> 转换为 QByteArray?

c++ - 圈子用户头像问题

c# - 当外部应用程序的窗口移动时移动窗口