如何利用web原理+VBA实现windows上面拷贝图片到粘贴板clipboard

376 阅读2分钟

如题。

参考了不少资料,工具是按键精灵。

方法1:dll加载

来源;www.vbforums.com/showthread.…

这个dll可以实现设置clip和读取clip的功能,把这个dll拖入精灵的plugin目录可以调用。

设置text和读取text测试成功,但是image的话,不知道怎么弄;放弃。

方法2:大漠?没有测试过。

方法3:www.irfanview.com/64bit.htm 下载软件,自带cmd工具,如下可以把clip保存图片到文件夹,如下

image.png

上面都没有完全解决问题,我需要把图片拷贝到clipboard。

方法四:回归原始的考古贴,关于原生的网页版拷贝图片,ie有个bug,运行execommand拷贝到用户clipboard。

JS代码网上很多,vb的代码少的可怜,终于搞定,如下,原理跟js差不多,自己解读:


网上独一份的代码,拷贝的时候几个给个赞 26996579 &qq.com

Function SetCLBPIC(PicFileSpec)

Set fso = CreateObject("Scripting.FileSystemObject") '创建fso对象

Dim HtmlPath, Str '定义变量

HtmlPath = "C:\tmp\copy-img-tmp.html" '临时文件路径,可修改(从环境变量中取更可靠)

Str = "<!DOCTYPE> <html> <body><img id='imgid' name='image' src='"& PicFileSpec &"' /></body> </html>"

If fso.FileExists(HtmlPath) Then

  fso.DeleteFile HtmlPath, true '删除可能存在的同名html

End If


Call GenerateNewHtml(HtmlPath, Str) '在html中写入Str

Set ie = CreateObject("InternetExplorer.Application")'创建IE对象


ie.navigate HtmlPath
             'ie.visible=true

Do While ie.ReadyState <> 4
Loop

iL = ie.Document.all.Length


For I = 1 To iL
On Error Resume Next
strTmp = ie.Document.all(I).getAttribute("name")
If InStr(1, strTmp, "image", vbTextCompare) > 0 Then
iIndex = I
Exit For  'found then  break
End If
Next


 

Set controlRange = ie.Document.body.createControlRange()

'Call controlRange.Add( ie.Document.getElementById("imgid"))

Call controlRange.Add( ie.Document.all(iIndex))

Call controlRange.execCommand("Copy")

 
Delay(100)

 

ie.Quit 'IE对象退出

Set ie = nothing '释放

fso.DeleteFile HtmlPath, true '强删

Set fso = nothing '释放

End Function
'生成html文件


Sub GenerateNewHtml(HtmlsPath, tStr)
Set fso = CreateObject("Scripting.FileSystemObject")
'Set objFile = fso.CreateTextFile(HtmlsPath) '创建文件
Set ttfile = fso.OpenTextFile(HtmlsPath, 2, True) '以写方式打开文件
ttfile.Write tStr
ttfile.Close
End Sub

Call SetCLBPIC("C:\tmp\a.jpg")

小声说一句,师傅一般都会留下两手,即使你拷贝了上面代码也不一定能用,因为还有下面两个拦路虎。

  1. IE虽然有漏洞,但是人家也很机智,首选ie会提醒你的网页要用你的clipboard,需要点击运行。显然不方便,我不可能每次都点击,而且需要打开is.Visible=true才能看到(大坑)。。。怎么解决,如下:

image.png

  1. 还没有完,等你运行的时候再次报错说,content被禁止,需要这里打开。

image.png

  1. 等等,还没有完。等你运行的时候还是不能用。。。。。需要看看小星星,提示你重启电脑才生效。。。。

至此,完美解决。。。。太多坑!!!