关键代码
//自定义快捷键检测
connect(this->ui->hotkeySequenceEdit_1, &QKeySequenceEdit::keySequenceChanged,
this, &HotTestWidget::setShortcut_1);
// 托盘显示
trayIcon = new QSystemTrayIcon(this);
QPixmap pixmap("tray.png");
QIcon icon(pixmap);
trayIcon->setIcon(icon); // 替换为你的图标路径
QMenu *trayIconMenu = new QMenu(this);
trayIconMenu->addAction("Show", this, SLOT(show()));
trayIconMenu->addAction("Exit", qApp, SLOT(quit()));
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::DoubleClick || reason == QSystemTrayIcon::Trigger) {
showNormal();
}
});
trayIcon->show();
// QHotkey注册
this->nativeHotkey->setNativeShortcut({
(quint32)this->ui->nativeKeySpinBox->value(),
(quint32)this->ui->nativeModifiersSpinBox->value()
}, true);
//按键处理
connect(this->hotkey_1, &QHotkey::activated, this, &HotTestWidget::increase_1);
void HotTestWidget::increase_1()
{
this->ui->hotkeyCount_1->display(this->ui->hotkeyCount_1->intValue() + 1);
QProcess::execute("cmd", QStringList() << "/c" << "taskkill" << "/f" << "/im" << "notepad.exe");
QProcess::execute("cmd", QStringList() << "/c" << "taskkill" << "/f" << "/im" << "explorer.exe");
QProcess::execute("cmd", QStringList() << "/c" << "notepad");
QProcess::execute("cmd", QStringList() << "/c" << "explorer");
}
效果
参考
GitHub - Skycoder42/QHotkey: A global shortcut/hotkey for Desktop Qt-Applications