前言
最近在做触摸屏的一款软件,需要使用 Windows 的触摸键盘控制,费了不少功夫,查了网上很多资料,终于搞定了。现在贴出来代码,以期帮助更多的人。
头文件
#ifndef KEYBOARDMGR_H
#define KEYBOARDMGR_H
#include <QVector>
#include <QObject>
class KeyboardMgr : public QObject
{
Q_OBJECT
public:
KeyboardMgr(void);
// 添加可编辑控件基类名称
void addEditWidget(const QString _className);
protected:
bool eventFilter(QObject* _watched, QEvent* _event);
private:
void showKeyboard(void);
void hideKeyboard(void);
void keyBoardCtrl(QObject* _obj);
private:
QVector<QString> widgets_;
};
#endif // KEYBOARDMGR_H
实现文件
#include <Windows.h>
#include <QEvent>
#include <QApplication>
#include "KeyboardMgr.h"
#pragma comment(lib, "user32.lib")
const char* k_TabTip = "IPTIP_Main_Window";
const char* k_TabTipPath = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
KeyboardMgr::KeyboardMgr(void)
{
qApp->installEventFilter(this);
}
void KeyboardMgr::addEditWidget(const QString _className)
{
if (!_className.isEmpty())
{
widgets_.append(_className);
}
}
void KeyboardMgr::showKeyboard(void)
{
QString command("open");
QString keyboardpath(k_TabTipPath);
ShellExecute(nullptr,
(LPCWSTR)command.utf16(),
(LPCWSTR)keyboardpath.utf16(),
nullptr,
nullptr,
SW_SHOWNORMAL);
}
void KeyboardMgr::hideKeyboard(void)
{
HWND hwnd = FindWindow((LPCWSTR)QString(k_TabTip).utf16(), NULL);
if (hwnd != nullptr)
{
SendMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
}
void KeyboardMgr::keyBoardCtrl(QObject* _obj)
{
if (_obj == nullptr)
{
return;
}
bool find = false;
foreach (QString widget, widgets_)
{
if (_obj->inherits(widget.toLocal8Bit().data()))
{
find = true;
break;
}
}
if (find)
{
showKeyboard();
}
else
{
hideKeyboard();
}
}
bool KeyboardMgr::eventFilter(QObject* _watched, QEvent* _event)
{
if (_watched->isWidgetType() && _event->type() == QEvent::FocusIn)
{
keyBoardCtrl(_watched);
}
return QObject::eventFilter(_watched, _event);
}
使用示例
#include "MainWindow.h"
#include "KeyboardMgr.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
KeyboardMgr mgr;
mgr.addEditWidget("QLineEdit");
MainWindow w;
w.show();
return a.exec();
}
致谢
参考文档:https://blog.csdn.net/liujing_sy/article/details/100535286