方法1
Watir API 本身提供了截图函数ScreenCapture, 可以直接使用,调用时会打开mspaint然后自动保存到指定路径
由于项目特殊要求,截图要直接保存到PPT当中,所以借用了ScreenCapture的一些代码, 再通过win32ole打开PPT, 并保存图片。
一些代码片断如下
require 'win32ole'
require 'watir'
def shot_screen
ie = Watir::IE.attach(:title, /regular expression/) # attach the window that you want
ie.bring_to_front # so it can be captured
# open the ppt and add a new slide, user
ppt = WIN32OLE.new('Powerpoint.Application')
ppt.visible = TRUE
pre = ppt.Presentations.Open "c://test.ppt"
ppt.ActivePresentation.Slides.Add(1,1)
# 使用键盘操作来截图,下面代码不能直接运行,请参考 watir/screen_capture.rb
# Ctrl + V : Paste
keybd_event.Call(VK_CONTROL, 1, 0, 0)
keybd_event.Call(vkKeyScan.Call(?V), 1, 0, 0)
keybd_event.Call(vkKeyScan.Call(?V), 1, KEYEVENTF_KEYUP, 0)
keybd_event.Call(VK_CONTROL, 1, KEYEVENTF_KEYUP, 0)
sleep(1)
end
方法2: 使用win32screenshot
通过gem install win32screenshot 安装
然后利用如下代码来截图并保存
require 'win32screenshot'
ie=Watir::IE.attach(:title, /reqular expression/)
ie.bring_to_front
bmp = Win32::Screenshot.capture_hwnd(ie.hwnd)
width,height,bmp = Win32::Screenshot.capture_hwnd(ie.hwnd)
File.open('C:/screenshot.bmp', "wb"){|io| io.write(bmp)}
运行后bmp格式的图片会被保存到指定路径
另注:
1. 还可以利用 'RMagick' 对截图进行处理,可以在网上查到相关资料。安装RMagick可能会碰到点麻烦,参考其index文件
下载win32screenshot: http://rubyforge.org/projects/win32screenshot/
下载Rmagick http://rubyforge.org/projects/rmagick/
2. 有时候想要截图的内容并没有显示在窗口内,某些时候可以利用下面的代码来scroll页面使其显示
ie.link(:text, '').document.srollintoview