Найти - Пользователи
Полная версия: Получить текст под курсором
Начало » Python для новичков » Получить текст под курсором
1
gonnpkf
Добрый день.
Используется win32, python 3.3. Необходимо получить текст под курсором мыши в любом окне. Позиция курсора отслеживается, но вот с текстом возникла проблема. Возможно ли это? Если да, то как это лучше сделать?
vanvanov
Я это делаю примерно так:

#!/usr/bin/python3
import tkinter as tk
# вернуть выделенный фрагмент
def show_sel(title,text):
	root=tk.Tk()
	def callback_sel():
		res[0]=txt.get('sel.first','sel.last').replace('\n','')
		top.destroy()
		root.deiconify()
	top, res = tk.Toplevel(root), [None]
	root.withdraw()
	top.title(title)
	frame=tk.Frame(top)
	frame=tk.Frame(top)
	frame.pack(side='bottom',expand=1,fill='both')
	scrollbar=tk.Scrollbar(frame,jump=0)
	txt=tk.Text(frame,font='Arial 14',wrap='word',yscrollcommand=scrollbar.set)
	txt.insert('end',text)
	scrollbar.config(command=txt.yview)
	scrollbar.pack(side='right',fill='y')
	txt.pack(expand=1,fill='both')
	txt.bind('<Return>', lambda e: callback_sel())
	txt.focus_set()
	button=tk.Button(frame,text='Выделенное',command=callback_sel)
	button.bind('<Return>', lambda e: callback_sel())
	button.pack()
	top.wait_window(top)
	return res[0]
print(show_sel('Выделите текст:','Привет, python.su. Как поживаешь?'))
gonnpkf
Спасибо. Только текст нужно получать не выделенный и не в окне приложения.
Приблизительно нужный код найден. Но он требует comtypes, которого для python 3.3 64bit вроде как нет. В частности оттуда нужен VARIANT(). Может есть альтернативы?
sanodin
comtypes - Pure Python COM package, based on the ctypes FFI library.

comtypes allows to define, call, and implement custom COM interfaces
in pure Python. It works on Windows, 64-bit Windows, and Windows CE
http://sourceforge.net/projects/comtypes/files/comtypes/0.6.2/comtypes-0.6.2.zip/download
import sys, time
from ctypes import windll, oledll, WinError, byref, POINTER
from ctypes.wintypes import POINT
from comtypes import COMError
from comtypes.automation import VARIANT
from comtypes.client import GetModule
# create wrapper for the oleacc.dll type library
GetModule("oleacc.dll")
# import the interface we need from the wrapper
from comtypes.gen.Accessibility import IAccessible
def GetCursorPos():
    "Return the cursor coordinates"
    pt = POINT()
    if not windll.user32.GetCursorPos(byref(pt)):
        raise WinError()
    return pt.x, pt.y
def AccessibleObjectFromPoint(x, y):
    "Return an accessible object and an index. See MSDN for details."
    pacc = POINTER(IAccessible)()
    var = VARIANT()
    oledll.oleacc.AccessibleObjectFromPoint(POINT(x, y), byref(pacc), byref(var))
    return pacc, var
if __name__ == "__main__":
    while 1:
        time.sleep(1)
        x, y = GetCursorPos()
        try:
            pacc, index = AccessibleObjectFromPoint(x, y)
            name = pacc.accName[index]
        except (WindowsError, COMError), details:
            print details
            continue
        if name is not None:
            print "===", (x, y), "=" * 60
            print name.encode(sys.stdout.encoding, "backslashreplace")
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB