Skip to content

Instantly share code, notes, and snippets.

@Mte90
Created April 2, 2025 08:46
Show Gist options
  • Save Mte90/98bfc01d3445c343dea7bc8b8f0d5e49 to your computer and use it in GitHub Desktop.
Save Mte90/98bfc01d3445c343dea7bc8b8f0d5e49 to your computer and use it in GitHub Desktop.
QtKeyLogger
cmake_minimum_required(VERSION 3.16)
project(QtKeyLogger LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 REQUIRED COMPONENTS Widgets)
qt_standard_project_setup()
add_executable(QtKeyLogger
hotkey.cpp
hotkey.h
)
set_property(SOURCE hotkey.h PROPERTY SKIP_AUTOMOC OFF)
set_property(SOURCE hotkey.cpp PROPERTY SKIP_AUTOMOC OFF)
target_link_libraries(QtKeyLogger PRIVATE Qt6::Widgets)
#include "hotkey.h"
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QKeyEvent>
KeyPressWidget::KeyPressWidget(QWidget *parent) : QWidget(parent) {
QVBoxLayout *layout = new QVBoxLayout(this);
label = new QLabel("Press a key", this);
layout->addWidget(label);
setLayout(layout);
resize(400, 400);
}
KeyPressWidget::~KeyPressWidget() {}
void KeyPressWidget::keyPressEvent(QKeyEvent *event) {
QString keyText;
const Qt::KeyboardModifier modifiers[] = {
Qt::ShiftModifier, Qt::ControlModifier, Qt::AltModifier, Qt::MetaModifier
};
const QString modifierNames[] = { "Shift", "Ctrl", "Alt", "Meta" };
for (int i = 0; i < 4; ++i) {
if (event->modifiers() & modifiers[i]) {
keyText += modifierNames[i] + "+";
}
}
keyText += QKeySequence(event->key()).toString(QKeySequence::NativeText);
label->setText("Key Pressed: " + keyText);
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
KeyPressWidget window;
window.show();
return app.exec();
}
#ifndef HOTKEY_H
#define HOTKEY_H
#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QKeyEvent>
class KeyPressWidget : public QWidget {
Q_OBJECT
public:
explicit KeyPressWidget(QWidget *parent = nullptr);
virtual ~KeyPressWidget(); // Explicitly declare a virtual destructor
protected:
void keyPressEvent(QKeyEvent *event) override;
private:
QLabel *label;
};
#endif // HOTKEY_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment