Copy unformatted plain text to the clipboard using VBScript

社会主义新天地 提交于 2020-01-06 12:43:42

问题


I'm using the following function in my VBScript to copy a string onto the clipboard without the use of the external clip command (which isn't and cannot be installed due to security policies):

Function CopyToClipboard(sText)
    Dim oWord : Set oWord = CreateObject("Word.Application")
    With oWord
        .Visible = False
        .Documents.Add
        .Selection.TypeText sText
        .Selection.WholeStory
        .Selection.Copy
        .Quit False
    End With
    Set oWord = Nothing
End Function

The problem is that the string being copied comes with the standard formatting inherited by the "normal.dot" template.

Given that I have Word 2003, this formatting is Times New Roman, 12pt and in black. So when it gets pasted into an email or document, the formatting doesn't match with the existing content.

Is there any way to remove the formatting on the string in the clipboard?


回答1:


After playing around a bit, I developed a solution that doesn't use the Word object model, but does copy unformatted text to the clipboard - which is what I needed to do:

Function CopyToClipboard(sText)
    ' Create temporary text file to avoid IE clipboard warnings
    Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
    Dim sTemp : sTemp = fso.GetSpecialFolder(2) & "\" & fso.GetTempName
    Dim oFile : Set oFile = fso.CreateTextFile(sTemp, True)
    oFile.Write "This file can be safely deleted"
    oFile.Close
    Set oFile = Nothing

    ' Start Internet Explorer in the local zone
    Dim oIE : Set oIE = CreateObject("InternetExplorer.Application")
    oIE.Visible = 0
    oIE.Navigate2 sTemp
    Do
        WScript.Sleep 100
    Loop Until oIE.Document.ReadyState = "complete"

    ' Copy contents to clipboard
    oIE.Document.ParentWindow.ClipboardData.SetData "text", sText

    ' Clean up
    fso.DeleteFile sTemp
    Set oIE = Nothing
    Set fso = Nothing
End Function

This code uses Internet Explorer's ability to access the clipboard in order to paste in the contents of sText. You'll notice that about:blank isn't used as the starting page and this is because it will generate the following warning:

In order to get around this we create a temporary file locally (with some copy to indicate that it is benign) and then navigate to this file. As a result Internet Explorer treats this page in the "Local Intranet" zone and allows access to the clipboard without generating a pop-up confirmation.



来源:https://stackoverflow.com/questions/21135691/copy-unformatted-plain-text-to-the-clipboard-using-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!