0

I am using pyhook to detect when user presses Control + C. Then I get the data copied from the clipboard using win32clipboard api.

The problem I am facing is that the code returns the last copied data not the current one.

Is it because it takes time to save something in clipboard?

Here is my code:

from time import sleep
import win32clipboard
import win32api
import win32console
import win32gui
import pythoncom,pyHook
from threading import Thread

"""
win=win32console.GetConsoleWindow()
win32gui.ShowWindow(win,0)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
"""

data=''
def getcopied():
    global data
    while True:
        try:
            win32clipboard.OpenClipboard()
            data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
            break
        except TypeError:
            print "Copied Content Invalid"
            break
    if data.isalpha():
        print data


def initkeystack():
    global keystack
    keystack=[ [i,-1] for i in ['','','','','']]

def ctrlc():
    global keystack
    ct=0
    for i in range(5):
        if ct==0:
            if keystack[i]==['Lcontrol',0]:
                ct=1
        else:
            if keystack[i]==['C',0]:
                getcopied()
                getcopied()
                initkeystack()

def OnKeyboardEvent(event):
    str=event.GetKey()
    global keystack
    if keystack[4]!=[str,0]:
        del(keystack[0])
        keystack.append([str,0])
        ctrlc()

def OnKeyboardEventUp(event):
    str=event.GetKey()
    global keystack
    if keystack[4]!=[str,1]:
        del(keystack[0])
        keystack.append([str,1])
        ctrlc()

def klog():
    keystack=[]
    initkeystack()
    while True:
        try:
            hm=pyHook.HookManager()
            hm.KeyDown=OnKeyboardEvent
            hm.KeyUp=OnKeyboardEventUp
            hm.HookKeyboard()
            while True:
                pythoncom.PumpWaitingMessages()
        except KeyboardInterrupt:
            pass

a = Thread(target=klog)
a.start()
a.join()

1 Answers1

0

You can use ctypes to get the clipboard.

Here's a simple function that will return the clipboard if it has a string in it.

import ctypes           

user32 = ctypes.windll.user32       
kernel32 = ctypes.windll.kernel32   

def getClipboard(user32, kernel32):
    user32.OpenClipboard(0)
    if user32.IsClipboardFormatAvailable(1):
        data = user32.GetClipboardData(1)
        data_locked = kernel32.GlobalLock(data)
        clipText = ctypes.c_char_p(data_locked)
        kernel32.GlobalUnlock(data_locked)
        text = clipText.value
    else:
        text = ""
    user32.CloseClipboard()
    return text

print(getClipboard(user32, kernel32))
Ciprum
  • 734
  • 1
  • 11
  • 18