c++ - 如何访问静态函数 MouseProc、SetWindowsHookEx 中的 ui 结构(文本框、标签)?
问题描述
在我的 .h 文件函数中,mouseProc 被声明为静态(必须是)
.h 文件
static LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam);
最初我想我会添加 &ui 作为这个函数的参数,但我不能这样做。它给了我错误“与 HOOKPROC 不兼容的参数类型”
所以,现在我无法通过使用
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
指针存储在全局内存中,甚至也可以static
。mouseProc
可以到达的地方。
至于编译器错误,它说的是正确的-MainWindow
您显示的类没有名为 的成员textbox
,这就是访问ui->textbox
(无论来自何处ui
)无法编译的原因。因此,您需要找出textbox
真正存储的位置,然后从 THERE 而不是从MainWindow
.
推荐阅读
- java - 如何在txt文件中逐行捕获所有标题和字段信息并存储在结构或数组中
- c++ - 为什么 C++ 映射中没有“存在”函数?
- mysql - 将 GROUP BY 与聚合函数一起使用是否正确?
- node.js - 请求的资源上没有“Access-Control-Allow-Origin”标头,仅针对一个请求,其余 API 工作正常
- python-3.x - 在 Azure 函数中使用 cosmosdb python SDK
- python - ValueError:labels_true 必须是 1D?
- mysql - MySQL 每 50 行单列中的值总和
- laravel-8 - SQLSTATE [42S02]:未找到基表或视图:1146 表“cloud18i_dbpethu.sessions”不存在
- assembly - 0x00400258 处的 Mips 运行时异常:地址超出范围 0x00000068
- ffmpeg - FFMPEG 将视频并排分成两部分