Уведомления

Группа в Telegram: @pythonsu

#1 Май 19, 2014 17:14:57

gonnpkf
Зарегистрирован: 2013-04-25
Сообщения: 7
Репутация: +  0  -
Профиль   Отправить e-mail  

Получить текст под курсором

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

Офлайн

#2 Май 19, 2014 20:00:05

vanvanov
Зарегистрирован: 2013-03-31
Сообщения: 252
Репутация: +  4  -
Профиль   Отправить e-mail  

Получить текст под курсором

Я это делаю примерно так:

#!/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. Как поживаешь?'))

Офлайн

#3 Май 20, 2014 10:51:18

gonnpkf
Зарегистрирован: 2013-04-25
Сообщения: 7
Репутация: +  0  -
Профиль   Отправить e-mail  

Получить текст под курсором

Спасибо. Только текст нужно получать не выделенный и не в окне приложения.
Приблизительно нужный код найден. Но он требует comtypes, которого для python 3.3 64bit вроде как нет. В частности оттуда нужен VARIANT(). Может есть альтернативы?

Офлайн

#4 Май 20, 2014 12:19:54

sanodin
От:
Зарегистрирован: 2011-06-16
Сообщения: 515
Репутация: +  31  -
Профиль   Отправить e-mail  

Получить текст под курсором

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")

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version