如何在QT中获取后台应用程序窗口标题?

时间:2018-04-04 17:48:31

标签: c++ qt

在我的qt应用程序中按下按钮时,我需要显示后台应用程序窗口标题。目前我曾经以这样的方式管理它,在'setupUi'调用之前调用'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;
}

但是,这个代码的问题是,当后台应用程序窗口发生变化时,我需要重新启动应用程序以再次获取后台标题,因为需要在setupUi调用之前调用'getBackgroundWindowTitle'。

我正在寻找任何时候的解决方案,当用户按下按钮时,应该检索后台应用程序窗口标题。

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

1 个答案:

答案 0 :(得分:0)

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