-
Notifications
You must be signed in to change notification settings - Fork 251
python basic
qiannian edited this page Jun 13, 2026
·
1 revision
演示 Python 创建 COM 对象、绑定窗口、鼠标键盘、图色和 OCR 的基础调用流程。
from win32com.client import Dispatch
class Demo:
def __init__(self):
# 创建 COM 对象
self.op = Dispatch("op.opsoft")
self.hwnd = 0
self.send_hwnd = 0
print("init")
def test_base(self):
# 输出插件版本号和全局路径
print("op ver:", self.op.Ver())
print("path:", self.op.GetPath())
# 设置错误提示模式,并启动记事本
self.op.SetShowErrorMsg(2)
ret = self.op.WinExec("notepad", 1)
print("Exec notepad:", ret)
def test_window_api(self):
# 查找记事本窗口和编辑控件
self.hwnd = self.op.FindWindow("", "无标题 - 记事本")
print("parent hwnd:", self.hwnd)
if self.hwnd:
self.send_hwnd = self.op.FindWindowEx(self.hwnd, "Edit", "")
print("child hwnd:", self.send_hwnd)
def test_bkmode(self):
# 绑定窗口,后续后台鼠标键盘和图色接口会使用该窗口
ret = self.op.BindWindow(self.hwnd, "gdi", "normal", "normal", 0)
if ret == 0:
print("bind false")
return ret
def test_bkmouse_bkkeypad(self):
# 鼠标点击并向编辑控件发送字符串
self.op.MoveTo(200, 200)
self.op.Sleep(200)
self.op.LeftClick()
self.op.Sleep(1000)
ret = self.op.SendString(self.send_hwnd, "Hello World!")
print("SendString ret:", ret)
self.op.Sleep(1000)
def test_bkimage(self):
# 获取颜色、截图、找图
color = self.op.GetColor(30, 30)
print("color of (30,30):", color)
ret = self.op.Capture(0, 0, 2000, 2000, "screen.bmp")
print("op.Capture ret:", ret)
ret, x, y = self.op.FindPic(0, 0, 100, 100, "test.png", "000000", 1.0, 0)
print("op.FindPic:", ret, x, y)
def test_ocr(self):
# OCR 识别示例
text = self.op.OcrAuto(0, 0, 100, 100, 0.9)
print("ocr:", text)
text = self.op.OcrEx(0, 0, 100, 100, "000000-020202", 0.9)
print("OcrEx:", text)
text = self.op.OcrAutoFromFile("screen.bmp", 0.95)
print("OcrAutoFromFile:", text)
def test_clear(self):
# 使用完成后解除绑定
self.op.UnBindWindow()
def test_all():
demo = Demo()
demo.test_base()
demo.test_window_api()
if demo.test_bkmode() == 0:
return
demo.test_bkmouse_bkkeypad()
demo.test_bkimage()
demo.test_ocr()
demo.test_clear()
print("test begin")
test_all()
print("test end")