opc0de
opc0de

Reputation: 11768

Access class from function

Is there another way besides declaring a static method inside a class to call it from outside the class ?

Here is my code (See the question marked as comment )

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

_stdcall BOOL EnumWindowsProc(HWND hw,LPARAM lp)
{
    char title[255];

    memset(title,0,255);
    GetWindowTextA(hw,title,255);

    qDebug() << title << endl;

     // How can I access class MainWindow from this function ?   

    return true;
}

void MainWindow::on_pushButton_clicked()
{
    EnumWindows(&EnumWindowsProc,0);
}

Upvotes: 0

Views: 125

Answers (1)

John Dibling
John Dibling

Reputation: 101496

The typical way of doing this in the Windows world is to pass a pointer to the Enum function, like this:

void MainWindow::on_pushButton_clicked()
{
    EnumWindows(&EnumWindowsProc,reinterpret_cast<void*>(this));
}

...and then cast it back in the callback:

_stdcall BOOL EnumWindowsProc(HWND hw,LPARAM lp)
{
    char title[255];

    memset(title,0,255);
    GetWindowTextA(hw,title,255);

    qDebug() << title << endl;

     // How can I access class MainWindow from this function ?   

MainWindow* that = reinterpret_cast<MainWindow*>(lp);


    return true;
}

Upvotes: 2

Related Questions