如何在QT中获取背景应用程序窗口标题

How to get background application window title in QT?

本文关键字:背景 应用程序 窗口标题 获取 QT      更新时间:2023-10-16

在我的qt应用程序中,当我按下按钮时,我需要显示背景应用程序窗口标题。目前,我用来管理此操作,以便在"设置"调用之前调用" GetBackgroundWindowTitle"函数。因此,这为我返回了背景应用程序窗口标题。我目前的实现如下

MyWindow::MyWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MyWindow)
{
    g_window_title = getBackgroundWindowTitle();
    ui->setupUi(this);
}
void MyWindow::OnPushbuttonPressed()
{
    ui->labelBackgroundWindowTitle.setText(g_window_title);
}
QString MyWindow::getBackgroundWindowTitle()
{
    char buff[256];
    HWND hwnd = GetForegroundWindow(); //currently this gives my current application window title
    GetWindowText(hwnd, (LPWSTR) buff, 254);
    QString title = QString::fromWCharArray((const wchar_t *)buff);
    return title;
}

但是,此代码的问题是,当背景应用程序窗口更改时,我需要重新启动应用程序以再次获取背景标题,因为" GetBackgroundWindowTitle"需要在设置调用之前调用。

我正在寻找任何时间解决方案,以至于当用户按下按钮时,应检索背景应用程序窗口标题。

有人可以帮助我修改我的代码吗?

如果它是z-order中的上一个(或下一个,请参见链接(窗口,则可以使用: GetNextWindow,例如:

QString MyWindow::getBackgroundWindowTitle()
{
    char buff[256];
    HWND myHwnd = GetForegroundWindow();
    HWND hwnd = GetNextWindow(myHwnd, GW_HWNDNEXT);
    GetWindowText(hwnd, (LPWSTR) buff, 254);
    QString title = QString::fromWCharArray((const wchar_t *)buff);
    return title;
}

现在,如果我理解您的问题,您只需要将呼叫转到getBackgroundWindowTitle到您的按钮处理程序:

void MyWindow::OnPushbuttonPressed()
{
    ui->labelBackgroundWindowTitle.setText(getBackgroundWindowTitle());
}