如何访问静态函数MouseProc、SetWindowsHookEx中的ui结构(文本框、标签)



在我的.h文件中,函数mouseProc被声明为静态(必须是(

.h文件

static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);

起初我想我会添加&ui作为这个函数的参数,但我不能这样做;"与HOOKROC不兼容的参数类型";

因此,现在我无法使用
ui->textbox->apped();访问UI中的文本框和标签。如何解决此问题?

---根据使ui静态化的建议进行更新---------------

主窗口.h

#pragma once
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "windows.h"
#include "windowsx.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT                      //Used to handle events
Q_DISABLE_COPY(MainWindow) //added
public:
MainWindow(QWidget* parent = 0);
~MainWindow();                    //Destructor used to free resources
// Static method that will act as a callback-function
static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
//   BOOL InitializeUIAutomation(IUIAutomation** automation);
static Ui::MainWindow* ui; // declared static,pointing to UI class
private:
// hook handler
HHOOK mouseHook;
};
#endif // MAINWINDOW_H

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <Windows.h>
#include <UIAutomation.h>
using namespace std;
Ui::MainWindow* MainWindow::ui = 0;
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
//, ui(new Ui::MainWindow)
{
ui = new Ui::MainWindow();
ui->setupUi(this);

HINSTANCE hInstance = GetModuleHandle(NULL);
// Set hook
mouseHook = SetWindowsHookEx(WH_MOUSE_LL, &mouseProc, hInstance, 0);
// Check hook is correctly
if (mouseHook == NULL)
{
qWarning() << "Mouse Hook failed";
}
}
BOOL InitializeUIAutomation(IUIAutomation** automation)
{
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
(void**)automation);
return (SUCCEEDED(hr));
}
MainWindow::~MainWindow()
{
delete ui;
}
LRESULT CALLBACK MainWindow::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
ui->textbox->append(string);
}

您不能向mouseProc添加额外的参数。编译器不会接受它,它需要匹配SetWindowsHookEx()所期望的签名。如果你使用类型转换来强制编译器接受它,那么当钩子被调用时,操作系统仍然不知道如何在运行时用值填充新参数,你最终只会破坏调用堆栈,和/或破坏代码。

要执行您想要的操作,您只需将ui指针存储在全局内存中,甚至将其设置为staticmouseProc可以到达的某个地方。

至于编译器错误,它所说的是正确的——您所展示的MainWindow类没有名为textbox的成员,这就是为什么访问ui->textbox(无论ui来自哪里(都无法编译的原因。因此,您需要弄清楚textbox真正存储在哪里,然后从THERE而不是从MainWindow访问它。

最新更新