-
Notifications
You must be signed in to change notification settings - Fork 251
lua
qiannian edited this page Jun 13, 2026
·
3 revisions
使用 luacom 创建 op.opsoft COM 对象,并演示窗口、绑定、鼠标键盘和图色的基础调用。
-- 加载 luacom
local luacom = require("luacom")
-- 创建 op COM 对象
-- 这里要求 op 插件已经注册,或者当前进程已经提前完成免注册 setup
local op = luacom.CreateObject("op.opsoft")
if op == nil then
error("创建 op.opsoft 失败")
end
print("test begin")
-- 输出版本号和插件目录
print("op ver:", op:Ver())
print("base path:", op:GetBasePath())
-- 启动记事本
local ret = op:WinExec("notepad", 1)
print("WinExec:", ret)
op:Sleep(500)
-- 查找记事本窗口
local hwnd = op:FindWindow("", "无标题 - 记事本")
if hwnd == 0 then
print("未找到记事本窗口")
return
end
print("parent hwnd:", hwnd)
-- 查找记事本编辑控件
local edit_hwnd = op:FindWindowEx(hwnd, "Edit", "")
if edit_hwnd == 0 then
print("未找到编辑控件")
return
end
print("edit hwnd:", edit_hwnd)
-- 绑定窗口;Lua 中 0 也是真值,所以必须明确判断是否等于 1
ret = op:BindWindow(hwnd, "gdi", "windows", "windows", 0)
if ret ~= 1 then
print("BindWindow 失败:", ret)
return
end
-- 使用完成后解除绑定
local ok, err = pcall(function()
-- 发送文本
ret = op:SendString(edit_hwnd, "Hello World!")
print("SendString:", ret)
-- 鼠标点击和取色
op:MoveTo(30, 30)
op:LeftClick()
print("color:", op:GetColor(30, 30))
-- 截图保存到当前全局路径
ret = op:Capture(0, 0, 100, 100, "screen.bmp")
print("Capture:", ret)
end)
op:UnBindWindow()
if not ok then
error(err)
end
print("test end")- Lua 里只有
false和nil是假值,数字0也是真值,所以 op 接口返回值要明确判断ret == 1或ret ~= 0。 -
luacom.CreateObject("op.opsoft")默认依赖系统注册表中的 COM 注册信息。 - 如果要免注册使用,需要在
CreateObject之前先调用tools.dll导出的setupW或setupA,可以由 LuaJIT FFI 或宿主程序完成。 - 当前 Lua 进程、
tools.dll、op_x86.dll/op_x64.dll的位数必须一致。