Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from datetime import datetime
- import pythoncom
- import wmi
- from PyQt5. QtCore import QObject, QRunnable, QThreadPool, pyqtSignal
- from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QHeaderView
- class KeyboardDetectorSignals(QObject):
- keyboard_changed = pyqtSignal(str)
- class KeyboardDetector(QRunnable):
- def __init__(self):
- super().__init__()
- self.signals = KeyboardDetectorSignals()
- def run(self):
- pythoncom.CoInitialize()
- device_connected_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
- device_disconnected_wql = "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
- c = wmi.WMI()
- connected_watcher = c.watch_for(raw_wql=device_connected_wql)
- disconnected_watcher = c.watch_for(raw_wql=device_disconnected_wql)
- while True:
- try:
- connected = connected_watcher(timeout_ms=10)
- except wmi.x_wmi_timed_out:
- pass
- else:
- if connected:
- self.signals.keyboard_changed.emit("Keyboard connected.")
- try:
- disconnected = disconnected_watcher(timeout_ms=10)
- except wmi.x_wmi_timed_out:
- pass
- else:
- if disconnected:
- self.signals.keyboard_changed.emit("Keyboard disconnected.")
- class MainWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setGeometry(100, 100, 500, 500)
- self.setWindowTitle("Keyboard Logger")
- self.log_table = QTableWidget()
- self.log_table.setColumnCount(2)
- self.log_table.setShowGrid(True)
- self.log_table.setHorizontalHeaderLabels(["Time", "Event"])
- self.log_table.horizontalHeader().setStretchLastSection(True)
- self.log_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
- self.setCentralWidget(self.log_table)
- self.show()
- self.threadpool = QThreadPool()
- keyboard_detector = KeyboardDetector()
- keyboard_detector.signals.keyboard_changed.connect(self.add_row)
- self.threadpool.start(keyboard_detector)
- def add_row(self, event: str):
- now = datetime.now()
- datetime_string = now.strftime("%Y-%m-%d %H:%M:%S")
- row_count = self.log_table.rowCount()
- self.log_table.insertRow(row_count)
- self.log_table.setItem(row_count, 0, QTableWidgetItem(datetime_string))
- self.log_table.setItem(row_count, 1, QTableWidgetItem(event))
- def closeEvent(self):
- sys.exit(app.exec())
- def main():
- app = QApplication(sys.argv)
- window = MainWindow()
- app.exec()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement