├── README
├── keyview.libglade
├── keyview.py
└── pyxhook.py
/README:
--------------------------------------------------------------------------------
1 | pykeyview
2 | =========
3 |
4 | A simple OSD display using (pygtk) for displaying keystrokes.
5 | Possibly useful for screencasts or presentations (live coding!).
6 |
7 | Uses/includes ``pyxhook.py`` from pykeylogger.sf.net as such it
8 | is available under the terms of GPL2.
9 |
10 | requires
11 | ========
12 |
13 | python bindings for X >= 1.4
14 | xorg >= 1.7.6
15 |
16 | Note
17 | ====
18 |
19 | As per Bug 20500 [0] X record extension is borked on versions <
20 | 1.7.6(?). The author is running 1.7.6 and it is working again!
21 |
22 | 0 - http://bugs.freedesktop.org/show_bug.cgi?id=20500
23 |
24 | TODO
25 | ====
26 |
27 | * Move to cairo?
28 | * Catch ctr-c signal and kill thread - DONE
29 | * Right click context menu
30 |
31 | * Quit - DONE
32 | * Toggle listen - DONE
33 | * Transparency?
34 | * Font size control - DONE
35 | * Mapping to replaces chars/keystrokes - DONE
36 | * Only listen to certain app
37 |
38 | Similar Tools
39 | =============
40 |
41 | CommandLog mode is an emacs specific minor mode [1]
42 |
43 | key-mon is a linux utility more towards keyboard/mouse commands [2]
44 |
45 | 1 - http://www.emacswiki.org/emacs/CommandLogMode
46 | 2 - http://code.google.com/p/key-mon/
47 |
--------------------------------------------------------------------------------
/keyview.libglade:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | True
7 | mouse
8 | False
9 | True
10 | utility
11 | True
12 | fontselectiondialog1
13 | 0.8
14 |
15 |
16 |
17 | True
18 |
19 |
20 |
21 |
22 | True
23 | True
24 | GDK_POINTER_MOTION_MASK | GDK_STRUCTURE_MASK
25 | cursor
26 |
27 | True
28 | True
29 | start
30 | 40
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | 5
41 | Select OSD Font
42 | True
43 | normal
44 |
45 |
46 | True
47 | 5
48 | vertical
49 | 12
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | True
58 | True
59 | True
60 | True
61 | True
62 | True
63 |
64 |
65 |
66 |
67 | True
68 | True
69 | True
70 | True
71 | True
72 | True
73 |
74 |
75 |
76 |
77 | True
78 | True
79 | True
80 | True
81 | True
82 | True
83 |
84 |
85 |
86 |
89 |
90 |
--------------------------------------------------------------------------------
/keyview.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | from xml.sax.saxutils import escape, quoteattr
4 | import gtk, gtk.glade
5 | from time import time
6 |
7 | import pyxhook
8 |
9 | # Want to handle/show these in a nice emacsy way
10 | MODIFIERS = (
11 | 'Control_L',
12 | 'Control_R',
13 | 'Alt_L',
14 | 'Alt_R',
15 | 'Super_L',
16 | 'Mode_switch'
17 | )
18 |
19 | CHORD_PREFIXES = (
20 | 'f1-',
21 | 'f2-'
22 | )
23 |
24 | SHIFT_KEYS = (
25 | 'Shift_L',
26 | 'Shift_R',
27 | )
28 |
29 | # Alter the appearance of some key events
30 | KEY_MAP = {
31 | 'F1':'f1-',
32 | 'F2':'f2-',
33 | 'F3':'f3',
34 | 'F4':'f4',
35 | 'F5':'f5',
36 | 'F6':'f6',
37 | 'F7':'f7',
38 | 'F8':'f8',
39 | 'F9':'f9',
40 | 'F10':'f10',
41 | 'F11':'f11',
42 | 'F12':'f12',
43 | 'Return':'↲',
44 | 'Right': '→',
45 | 'Left': '←',
46 | 'Up': '↑',
47 | 'Down': '↓',
48 | 'Control_L':'Ctrl-',
49 | 'Control_R':'Ctrl-',
50 | 'Mode_switch':'Mod4-',
51 | 'Alt_L':'Alt-',
52 | 'Alt_R':'Alt-',
53 | 'Shift_L':'⇪-',
54 | 'Shift_R':'⇪-',
55 | 'space': ' ',
56 | 'parenleft': '(',
57 | 'parenright': ')',
58 | 'bracketleft': '[',
59 | 'bracketright': ']',
60 | 'braceleft': '{',
61 | 'braceright': '}',
62 | 'BackSpace': '⇤',
63 | 'Delete': 'DEL',
64 | 'Tab': '↹',
65 | 'bar': '|',
66 | 'minus': '-',
67 | 'plus': '+',
68 | 'asterisk': '*',
69 | 'equal': '=',
70 | 'less': '<',
71 | 'greater': '>',
72 | 'semicolon': ';',
73 | 'colon': ':',
74 | 'comma': ',',
75 | 'apostrophe': "'",
76 | 'quotedbl' : '"',
77 | 'underscore' : '_',
78 | 'numbersign' : '#',
79 | 'percent' : '%',
80 | 'exclam' : '!',
81 | 'period' : '.',
82 | 'slash' : '/',
83 | 'backslash' : '\\',
84 | 'question' : '?',
85 | 'adiaeresis': 'ä',
86 | 'odiaeresis': 'ö',
87 | 'udiaeresis': 'ü',
88 | 'ssharp': 'ß',
89 | 'ampersand': '&',
90 | 'section': '§',
91 | }
92 |
93 | def get_hook_manager():
94 | hm = pyxhook.HookManager()
95 | hm.HookKeyboard()
96 | hm.HookMouse()
97 | #hm.KeyDown = hm.printevent
98 | #hm.KeyUp = self.hook_manager_event #hm.printevent
99 | #hm.MouseAllButtonsDown = hm.printevent
100 | #hm.MouseAllButtonsUp = hm.printevent
101 | hm.start()
102 | return hm
103 |
104 |
105 | class GTKKeyView:
106 | def __init__(self, hm):
107 |
108 | xml = gtk.glade.XML('keyview.libglade')
109 | self.window = xml.get_widget('window1')
110 | self.window.connect('destroy', self.quit)
111 | self.key_strokes = xml.get_widget('label1')
112 | self.key_strokes.set_alignment(0, 0)
113 | self.menu = xml.get_widget('config-menu')
114 | self.font_dialog = xml.get_widget('fontselectiondialog1')
115 | self.font = 'Courier Bold 30' #None # text of font description from selection dialog
116 | self.init_menu()
117 | self.pressed_modifiers = {} # keep track of whats pushed
118 | self.hm = hm
119 | self.active = True
120 | hm.KeyDown = self.hook_manager_down_event
121 | hm.KeyUp = self.hook_manager_up_event
122 | xml.signal_autoconnect(self)
123 | self.max_lines = 3
124 | self.show_backspace = True
125 | self.show_shift = False
126 | self.keys = [] #stack of keys typed
127 | self.last_key = 0 # keep track of time
128 |
129 | def init_menu(self):
130 | self.font_item = gtk.MenuItem('set font...')
131 | self.font_item.connect('activate', self.font_select)
132 |
133 | self.on_item = gtk.CheckMenuItem('listening')
134 | self.on_item.set_active(True)
135 | self.on_item.connect('activate', self.toggle_active)
136 |
137 | self.quit_item = gtk.MenuItem('quit')
138 | self.quit_item.connect('activate', self.quit)
139 |
140 | for item in [self.font_item, self.on_item, self.quit_item]:
141 | self.menu.append(item)
142 | item.show()
143 |
144 | def font_select(self, widget):
145 | response = self.font_dialog.run()
146 | self.font_dialog.hide()
147 | self.font = self.font_dialog.get_font_name()
148 | cur_text = self.key_strokes.get_text()
149 | self.update_text(cur_text, self.font)
150 |
151 |
152 | def toggle_active(self, widget):
153 | # active is state after click
154 | self.active = widget.get_active()
155 |
156 |
157 | def quit(self, widget):
158 | self.hm.cancel()
159 | gtk.main_quit()
160 |
161 |
162 | def on_eventbox1_popup_menu(self, *args):
163 | self.menu.show()
164 |
165 | def on_eventbox1_button_press_event(self, widget, event):
166 | if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
167 | self.menu.popup(None, None, None, event.button, event.get_time())
168 |
169 | def update_text(self, text, font_desc=None):
170 | """
171 | see
172 | http://www.pygtk.org/docs/pygtk/class-gtklabel.html
173 | and
174 | http://www.pygtk.org/docs/pygtk/pango-markup-language.html
175 | """
176 | if font_desc:
177 | font_desc_text = 'font_desc=%s' % quoteattr(font_desc)
178 | else:
179 | font_desc_text = ''
180 | pango_markup = """%s""" % (font_desc_text, escape(text))
181 | self.key_strokes.set_markup(pango_markup)
182 |
183 | def hook_manager_up_event(self, event):
184 | if event.Key in self.pressed_modifiers:
185 | del self.pressed_modifiers[event.Key]
186 |
187 | def hook_manager_down_event(self, event):
188 | #hm.printevent(event)
189 | if self.active:
190 | e_key = event.Key
191 |
192 | # hack to deal with ctr modifiers in emacsy way
193 | modifiers = []
194 | postfix = ''
195 | for modifier in self.pressed_modifiers.keys():
196 | mod = KEY_MAP.get(modifier, modifier)
197 | if self.keys and not self.keys[-1].text == mod:
198 | modifiers.append(mod)
199 | postfix = ' '
200 |
201 | if e_key in MODIFIERS:
202 | self.pressed_modifiers[e_key] = 1
203 | elif e_key == 'BackSpace' and not self.show_backspace:
204 | if self.keys:
205 | self.keys.pop()
206 | elif e_key in SHIFT_KEYS:
207 | if self.show_shift:
208 | self.pressed_modifiers[e_key] = 1
209 | else:
210 | txt = KEY_MAP.get(e_key, e_key)
211 |
212 | prefix = ''.join(modifiers)
213 | txt = Text(txt, prefix, postfix)
214 |
215 | isseq = (
216 | len(self.keys) > 0 and
217 | (self.keys[-1].is_chord_prefix
218 | or
219 | self.keys[-1].is_char and time() - self.last_key < 1)
220 | )
221 |
222 | if not (txt.is_char and isseq):
223 | self.keys.append(Text("\n"))
224 |
225 | self.keys.append(txt)
226 |
227 | self.last_key = time()
228 |
229 |
230 | # limit line lengths
231 | self.keys = limit_text(self.keys, self.max_lines)
232 | new_text = ''.join([repr(x) for x in self.keys])
233 |
234 | self.update_text(new_text, self.font)
235 |
236 | def limit_text(text_list, max_lines):
237 | r"""
238 | >>> lines = [Text('\n')]*4
239 | >>> len(limit_text(lines, 2)) #only 1 newline is possible since we're limiting to two lines
240 | 1
241 | >>> lines = [Text(x) for x in 'foo\nbar\nbaz']
242 | >>> len(limit_text(lines, 2)) #from bar to end
243 | 7
244 |
245 | """
246 | # limit line lengths
247 | new_line_idx = [i for i,x in enumerate(text_list) if x.text == '\n']
248 | if len(new_line_idx) >= max_lines:
249 | new_start = new_line_idx[-max_lines] + 1
250 | text_list = text_list[new_start:]
251 | return text_list
252 |
253 | class Text(object):
254 | """Simple class to hold text and pre/postfix for it
255 | """
256 | def __init__(self, text, prefix='', postfix=''):
257 | self.text = text
258 | self.prefix = prefix
259 | self.postfix = postfix
260 |
261 | def __repr__(self):
262 | return '%s%s%s' %(self.prefix, self.text, self.postfix)
263 |
264 | @property
265 | def is_char(self):
266 | t = self.text
267 | return len(t) == 1 and (t.isalnum() or t.isspace())
268 | @property
269 | def is_chord_prefix(self):
270 | return self.text in CHORD_PREFIXES
271 |
272 | def main():
273 | gtk.gdk.threads_init()
274 | hm = get_hook_manager()
275 | view = GTKKeyView(hm)
276 | w = view.window
277 | w.resize(360, 150)
278 | w.set_keep_above(True) #ensure visibility
279 | w.show()
280 |
281 | try:
282 | gtk.main()
283 | except KeyboardInterrupt, e:
284 | # kill the hook manager thread
285 | view.hm.cancel()
286 |
287 | def test():
288 | import doctest
289 | doctest.testmod()
290 |
291 | if __name__ == '__main__':
292 | main()
293 |
294 |
295 |
296 |
--------------------------------------------------------------------------------
/pyxhook.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # from pykeylogger http://pykeylogger.sourceforge.net/
3 | #
4 | # pyxhook -- an extension to emulate some of the PyHook library on linux.
5 | #
6 | # Copyright (C) 2008 Tim Alexander
7 | #
8 | # This program is free software; you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation; either version 2 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program; if not, write to the Free Software
20 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 | #
22 | # Thanks to Alex Badea for writing the Record
23 | # demo for the xlib libraries. It helped me immensely working with these
24 | # in this library.
25 | #
26 | # Thanks to the python-xlib team. This wouldn't have been possible without
27 | # your code.
28 | #
29 | # This requires:
30 | # at least python-xlib 1.4
31 | # xwindows must have the "record" extension present, and active.
32 | #
33 | # This file has now been somewhat extensively modified by
34 | # Daniel Folkinshteyn
35 | # So if there are any bugs, they are probably my fault. :)
36 |
37 | import sys
38 | import os
39 | import re
40 | import time
41 | import threading
42 |
43 | from Xlib import X, XK, display, error
44 | from Xlib.ext import record
45 | from Xlib.protocol import rq
46 |
47 | #######################################################################
48 | ########################START CLASS DEF################################
49 | #######################################################################
50 |
51 | class HookManager(threading.Thread):
52 | """This is the main class. Instantiate it, and you can hand it KeyDown and KeyUp (functions in your own code) which execute to parse the pyxhookkeyevent class that is returned.
53 |
54 | This simply takes these two values for now:
55 | KeyDown = The function to execute when a key is pressed, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class.
56 | KeyUp = The function to execute when a key is released, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class.
57 | """
58 |
59 | def __init__(self):
60 | threading.Thread.__init__(self)
61 | self.finished = threading.Event()
62 |
63 | # Give these some initial values
64 | self.mouse_position_x = 0
65 | self.mouse_position_y = 0
66 | self.ison = {"shift":False, "caps":False}
67 |
68 | # Compile our regex statements.
69 | self.isshift = re.compile('^Shift')
70 | self.iscaps = re.compile('^Caps_Lock')
71 | self.shiftablechar = re.compile('^[a-z0-9]$|^minus$|^equal$|^bracketleft$|^bracketright$|^semicolon$|^backslash$|^apostrophe$|^comma$|^period$|^slash$|^grave$')
72 | self.logrelease = re.compile('.*')
73 | self.isspace = re.compile('^space$')
74 |
75 | # Assign default function actions (do nothing).
76 | self.KeyDown = lambda x: True
77 | self.KeyUp = lambda x: True
78 | self.MouseAllButtonsDown = lambda x: True
79 | self.MouseAllButtonsUp = lambda x: True
80 |
81 | self.contextEventMask = [X.KeyPress,X.MotionNotify]
82 |
83 | # Hook to our display.
84 | self.local_dpy = display.Display()
85 | self.record_dpy = display.Display()
86 |
87 | def run(self):
88 | # Check if the extension is present
89 | if not self.record_dpy.has_extension("RECORD"):
90 | print "RECORD extension not found"
91 | sys.exit(1)
92 | r = self.record_dpy.record_get_version(0, 0)
93 | print "RECORD extension version %d.%d" % (r.major_version, r.minor_version)
94 |
95 | # Create a recording context; we only want key and mouse events
96 | self.ctx = self.record_dpy.record_create_context(
97 | 0,
98 | [record.AllClients],
99 | [{
100 | 'core_requests': (0, 0),
101 | 'core_replies': (0, 0),
102 | 'ext_requests': (0, 0, 0, 0),
103 | 'ext_replies': (0, 0, 0, 0),
104 | 'delivered_events': (0, 0),
105 | 'device_events': tuple(self.contextEventMask), #(X.KeyPress, X.ButtonPress),
106 | 'errors': (0, 0),
107 | 'client_started': False,
108 | 'client_died': False,
109 | }])
110 |
111 | # Enable the context; this only returns after a call to record_disable_context,
112 | # while calling the callback function in the meantime
113 | self.record_dpy.record_enable_context(self.ctx, self.processevents)
114 | # Finally free the context
115 | self.record_dpy.record_free_context(self.ctx)
116 |
117 | def cancel(self):
118 | self.finished.set()
119 | self.local_dpy.record_disable_context(self.ctx)
120 | self.local_dpy.flush()
121 |
122 | def printevent(self, event):
123 | print event
124 |
125 | def HookKeyboard(self):
126 | pass
127 | # We don't need to do anything here anymore, since the default mask
128 | # is now set to contain X.KeyPress
129 | #self.contextEventMask[0] = X.KeyPress
130 |
131 | def HookMouse(self):
132 | pass
133 | # We don't need to do anything here anymore, since the default mask
134 | # is now set to contain X.MotionNotify
135 |
136 | # need mouse motion to track pointer position, since ButtonPress events
137 | # don't carry that info.
138 | #self.contextEventMask[1] = X.MotionNotify
139 |
140 | def processevents(self, reply):
141 | if reply.category != record.FromServer:
142 | return
143 | if reply.client_swapped:
144 | print "* received swapped protocol data, cowardly ignored"
145 | return
146 | if not len(reply.data) or ord(reply.data[0]) < 2:
147 | # not an event
148 | return
149 | data = reply.data
150 | while len(data):
151 | event, data = rq.EventField(None).parse_binary_value(data, self.record_dpy.display, None, None)
152 | if event.type == X.KeyPress:
153 | hookevent = self.keypressevent(event)
154 | self.KeyDown(hookevent)
155 | elif event.type == X.KeyRelease:
156 | hookevent = self.keyreleaseevent(event)
157 | self.KeyUp(hookevent)
158 | elif event.type == X.ButtonPress:
159 | hookevent = self.buttonpressevent(event)
160 | self.MouseAllButtonsDown(hookevent)
161 | elif event.type == X.ButtonRelease:
162 | hookevent = self.buttonreleaseevent(event)
163 | self.MouseAllButtonsUp(hookevent)
164 | elif event.type == X.MotionNotify:
165 | # use mouse moves to record mouse position, since press and release events
166 | # do not give mouse position info (event.root_x and event.root_y have
167 | # bogus info).
168 | self.mousemoveevent(event)
169 |
170 | #print "processing events...", event.type
171 |
172 | def keypressevent(self, event):
173 | matchto = self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))
174 | if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))): ## This is a character that can be typed.
175 | if self.ison["shift"] == False:
176 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)
177 | return self.makekeyhookevent(keysym, event)
178 | else:
179 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 1)
180 | return self.makekeyhookevent(keysym, event)
181 | else: ## Not a typable character.
182 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)
183 | if self.isshift.match(matchto):
184 | self.ison["shift"] = self.ison["shift"] + 1
185 | elif self.iscaps.match(matchto):
186 | if self.ison["caps"] == False:
187 | self.ison["shift"] = self.ison["shift"] + 1
188 | self.ison["caps"] = True
189 | if self.ison["caps"] == True:
190 | self.ison["shift"] = self.ison["shift"] - 1
191 | self.ison["caps"] = False
192 | return self.makekeyhookevent(keysym, event)
193 |
194 | def keyreleaseevent(self, event):
195 | if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))):
196 | if self.ison["shift"] == False:
197 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)
198 | else:
199 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 1)
200 | else:
201 | keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)
202 | matchto = self.lookup_keysym(keysym)
203 | if self.isshift.match(matchto):
204 | self.ison["shift"] = self.ison["shift"] - 1
205 | return self.makekeyhookevent(keysym, event)
206 |
207 | def buttonpressevent(self, event):
208 | #self.clickx = self.rootx
209 | #self.clicky = self.rooty
210 | return self.makemousehookevent(event)
211 |
212 | def buttonreleaseevent(self, event):
213 | #if (self.clickx == self.rootx) and (self.clicky == self.rooty):
214 | ##print "ButtonClick " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty)
215 | #if (event.detail == 1) or (event.detail == 2) or (event.detail == 3):
216 | #self.captureclick()
217 | #else:
218 | #pass
219 |
220 | return self.makemousehookevent(event)
221 |
222 | # sys.stdout.write("ButtonDown " + str(event.detail) + " x=" + str(self.clickx) + " y=" + str(self.clicky) + "\n")
223 | # sys.stdout.write("ButtonUp " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty) + "\n")
224 | #sys.stdout.flush()
225 |
226 | def mousemoveevent(self, event):
227 | self.mouse_position_x = event.root_x
228 | self.mouse_position_y = event.root_y
229 |
230 | # need the following because XK.keysym_to_string() only does printable chars
231 | # rather than being the correct inverse of XK.string_to_keysym()
232 | def lookup_keysym(self, keysym):
233 | for name in dir(XK):
234 | if name.startswith("XK_") and getattr(XK, name) == keysym:
235 | return name.lstrip("XK_")
236 | return "[%d]" % keysym
237 |
238 | def asciivalue(self, keysym):
239 | asciinum = XK.string_to_keysym(self.lookup_keysym(keysym))
240 | if asciinum < 256:
241 | return asciinum
242 | else:
243 | return 0
244 |
245 | def makekeyhookevent(self, keysym, event):
246 | storewm = self.xwindowinfo()
247 | if event.type == X.KeyPress:
248 | MessageName = "key down"
249 | elif event.type == X.KeyRelease:
250 | MessageName = "key up"
251 | return pyxhookkeyevent(storewm["handle"], storewm["name"], storewm["class"], self.lookup_keysym(keysym), self.asciivalue(keysym), False, event.detail, MessageName)
252 |
253 | def makemousehookevent(self, event):
254 | storewm = self.xwindowinfo()
255 | if event.detail == 1:
256 | MessageName = "mouse left "
257 | elif event.detail == 3:
258 | MessageName = "mouse right "
259 | elif event.detail == 2:
260 | MessageName = "mouse middle "
261 | elif event.detail == 5:
262 | MessageName = "mouse wheel down "
263 | elif event.detail == 4:
264 | MessageName = "mouse wheel up "
265 | else:
266 | MessageName = "mouse " + str(event.detail) + " "
267 |
268 | if event.type == X.ButtonPress:
269 | MessageName = MessageName + "down"
270 | elif event.type == X.ButtonRelease:
271 | MessageName = MessageName + "up"
272 | return pyxhookmouseevent(storewm["handle"], storewm["name"], storewm["class"], (self.mouse_position_x, self.mouse_position_y), MessageName)
273 |
274 | def xwindowinfo(self):
275 | try:
276 | windowvar = self.local_dpy.get_input_focus().focus
277 | wmname = windowvar.get_wm_name()
278 | wmclass = windowvar.get_wm_class()
279 | wmhandle = str(windowvar)[20:30]
280 | except:
281 | ## This is to keep things running smoothly. It almost never happens, but still...
282 | return {"name":None, "class":None, "handle":None}
283 | if (wmname == None) and (wmclass == None):
284 | try:
285 | windowvar = windowvar.query_tree().parent
286 | wmname = windowvar.get_wm_name()
287 | wmclass = windowvar.get_wm_class()
288 | wmhandle = str(windowvar)[20:30]
289 | except:
290 | ## This is to keep things running smoothly. It almost never happens, but still...
291 | return {"name":None, "class":None, "handle":None}
292 | if wmclass == None:
293 | return {"name":wmname, "class":wmclass, "handle":wmhandle}
294 | else:
295 | return {"name":wmname, "class":wmclass[0], "handle":wmhandle}
296 |
297 | class pyxhookkeyevent:
298 | """This is the class that is returned with each key event.f
299 | It simply creates the variables below in the class.
300 |
301 | Window = The handle of the window.
302 | WindowName = The name of the window.
303 | WindowProcName = The backend process for the window.
304 | Key = The key pressed, shifted to the correct caps value.
305 | Ascii = An ascii representation of the key. It returns 0 if the ascii value is not between 31 and 256.
306 | KeyID = This is just False for now. Under windows, it is the Virtual Key Code, but that's a windows-only thing.
307 | ScanCode = Please don't use this. It differs for pretty much every type of keyboard. X11 abstracts this information anyway.
308 | MessageName = "key down", "key up".
309 | """
310 |
311 | def __init__(self, Window, WindowName, WindowProcName, Key, Ascii, KeyID, ScanCode, MessageName):
312 | self.Window = Window
313 | self.WindowName = WindowName
314 | self.WindowProcName = WindowProcName
315 | self.Key = Key
316 | self.Ascii = Ascii
317 | self.KeyID = KeyID
318 | self.ScanCode = ScanCode
319 | self.MessageName = MessageName
320 |
321 | def __str__(self):
322 | return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nKey Pressed: " + str(self.Key) + "\nAscii Value: " + str(self.Ascii) + "\nKeyID: " + str(self.KeyID) + "\nScanCode: " + str(self.ScanCode) + "\nMessageName: " + str(self.MessageName) + "\n"
323 |
324 | class pyxhookmouseevent:
325 | """This is the class that is returned with each key event.f
326 | It simply creates the variables below in the class.
327 |
328 | Window = The handle of the window.
329 | WindowName = The name of the window.
330 | WindowProcName = The backend process for the window.
331 | Position = 2-tuple (x,y) coordinates of the mouse click
332 | MessageName = "mouse left|right|middle down", "mouse left|right|middle up".
333 | """
334 |
335 | def __init__(self, Window, WindowName, WindowProcName, Position, MessageName):
336 | self.Window = Window
337 | self.WindowName = WindowName
338 | self.WindowProcName = WindowProcName
339 | self.Position = Position
340 | self.MessageName = MessageName
341 |
342 | def __str__(self):
343 | return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nPosition: " + str(self.Position) + "\nMessageName: " + str(self.MessageName) + "\n"
344 |
345 | #######################################################################
346 | #########################END CLASS DEF#################################
347 | #######################################################################
348 |
349 | if __name__ == '__main__':
350 | hm = HookManager()
351 | hm.HookKeyboard()
352 | hm.HookMouse()
353 | hm.KeyDown = hm.printevent
354 | hm.KeyUp = hm.printevent
355 | hm.MouseAllButtonsDown = hm.printevent
356 | hm.MouseAllButtonsUp = hm.printevent
357 | hm.start()
358 | time.sleep(10)
359 | hm.cancel()
360 |
--------------------------------------------------------------------------------