How can I use Clipboard in vbscript? [duplicate] - vbscript

This question already has answers here:
Use clipboard from VBScript
(15 answers)
How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
(6 answers)
Closed 3 years ago.
Editor's note:
While this question is specifically about copying a file reference to the clipboard, its generic title led to answers about how to copy / get text.
As an Emacs user on Windows who often attaches files in mails, I have been looking for a utility to copy a file (not its contents) to the clipboard, just as windows explorer does on righclick/copy).
I just found this right here on SO which uses System.Windows.Forms.Clipboard` in a small program to do exactly that. But it is in C#, for which I don't have immediate access to a compiler. So I am wondering if this can be done and how.
I saw several references such as this that the clipboard is not accessible in VBScripting, but msdn shows documentation for VB so I am risking the question.
I have never written a VBScript before but I did try a few things before asking, starting with running a copy pasted a "Hello world" and then various combinations of CreateObject etc.
Update: I need to call Clipboard.SetFileDropList, so I do not think I can use ClipboardData as suggested by the answers, it does not have this method.
Update for visitors
The solution I ended up using was to compile the C# itself, I did not know I already had a compiler.
Another update for visitors
https://stackoverflow.com/a/29963268/18573 is what I am now using, quite happily.

You can do it with an html object to retrieve the contents of the clipboard:
' Get clipboard text
Set objHTML = CreateObject("htmlfile")
text = objHTML.ParentWindow.ClipboardData.GetData("text")
EDIT: I use this snippet to put text back on the clipboard, but it needs third party software; a standalone executable 'clip.exe' which can be found on Windows 2003 Server or just on the internet:
' Do something with the text
text = replace(text, "you ", "you and your dog ")
' Put it back to the clipboard
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine text
oIn.Close
(Yes, it is all a little bit hackerdyhack)

VBScript doesn't support the clipboard. Most hosts that host vbscript, such as Internet Explorer give access through the host. Therefore vbscript running in IE or an HTA can use IE's clipboard support. The scripting hosts do not give clipboard support. You can use a vbs file to start IE through COM automation, navigate to a local page (to bypass security warnings), then use IE's clipboard.
Here's a code snippit (Outp. is a text stream)
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate2 "C:\Users\David Candy\Desktop\Filter.html"
Do
wscript.sleep 100
Loop until ie.document.readystate = "complete"
txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
ie.quit
If IsNull(txt) = true then
outp.writeline "No text on clipboard"
else
outp.writeline txt
End If

You need this function (is a little modification of this):
'TO CLEAR
ClipBoard("")
'TO SET
ClipBoard("Hello World!")
'TO GET
Result = ClipBoard(Null)
Function ClipBoard(input)
'#description: A quick way to set and get your clipboard.
'#author: Jeremy England (SimplyCoded)
If IsNull(input) Then
ClipBoard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text")
If IsNull(ClipBoard) Then ClipBoard = ""
Else
CreateObject("WScript.Shell").Run _
"mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _
& Replace(Replace(Replace(input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _
0,True
End If
End Function

For the equivalent of a "paste" operation I would run a command-line utility like ClipOut or paste, redirect output to a file and read the file contents.
return = WshShell.Run("cmd /c clipout.exe > output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("output.txt", 1)
text = file.ReadAll
file.Close
You can get ClipOut here: http://jasonfaulkner.com/ClipOut.aspx
You can get paste here: https://www.c3scripts.com/tutorials/msdos/paste.html
For the equivalent of a "copy" operation I would use the clip command line utility that actually comes with Windows and similar code as above.
About the clip utility: https://blogs.msdn.microsoft.com/oldnewthing/20091110-00/?p=16093

Related

Open a file with notepad and save it, using vbscript

My problem is that I want to open a file in notepad and then save it from notepad, not manually but using vbscript (the reason I want this is to overcome some encoding issues). Until now I have found a relevant article which should solve my problem, but it doesn't work. It has this code:
Dim notepad, wndNotepad, strDesktop
Set notepad = Sys.Process("notepad")
Set wndNotepad = notepad.Window("Notepad")
' Open a file in Notepad
wndNotepad.MainMenu.Click("File|Open...")
notepad.Window("#32770", "Open").OpenFile "C:\Program Files\SmartBear\TestComplete 12\install.txt"
' Save the file to the desktop
strDesktop = WshShell.SpecialFolders("Desktop")
wndNotepad.MainMenu.Click "File|Save as..."
notepad.Window("#32770", "Save As").SaveFile strDesktop & "\install.txt"
The problem is that vbscript can't recognize the Sys in the second line (Sys.Process). I assume that in this line a process for notepad should be created (like here) and then something like an object of this process to be returned to the variable notepad (something I don't know if and how can be achived) in order to be used in the third line (notepad.Window("Notepad")).
If anyone has any idea how the code should be in order to work, I would really appreciate the help. Also any other suggestions on how to solve this problem (or any ideas about if it can actually be solved) are very welcome. Thank you for your time.
EDIT
As I said in the comments below, the above code needs the TestComplete software which is expensive. So if anyone has any idea for resolving my issue in another way (other software, other code, other programming language) I would be glad to learn it.
I think you need to copy a file from one path to another. Please refer the below code for copying Files,
Function CopyFile()
strSourceFile = "c:\.....\source.txt"
strDestFile = "c:\.....\dest.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file is read-only
If Not fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is not read-only. Safe to replace the file.
fso.CopyFile strSourceFile, strDestFile, strOverWrite
Else
'The file exists and is read-only.
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
'Replace the file
fso.CopyFile strSourceFile, strDestFile, strOverWrite
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
End Function

How to store the contents of the clipboard into a variable? [duplicate]

This question already has answers here:
Use clipboard from VBScript
(15 answers)
How to copy/cut a file (not the contents) to the clipboard in Windows on the command line?
(6 answers)
Closed 3 years ago.
Editor's note:
While this question is specifically about copying a file reference to the clipboard, its generic title led to answers about how to copy / get text.
As an Emacs user on Windows who often attaches files in mails, I have been looking for a utility to copy a file (not its contents) to the clipboard, just as windows explorer does on righclick/copy).
I just found this right here on SO which uses System.Windows.Forms.Clipboard` in a small program to do exactly that. But it is in C#, for which I don't have immediate access to a compiler. So I am wondering if this can be done and how.
I saw several references such as this that the clipboard is not accessible in VBScripting, but msdn shows documentation for VB so I am risking the question.
I have never written a VBScript before but I did try a few things before asking, starting with running a copy pasted a "Hello world" and then various combinations of CreateObject etc.
Update: I need to call Clipboard.SetFileDropList, so I do not think I can use ClipboardData as suggested by the answers, it does not have this method.
Update for visitors
The solution I ended up using was to compile the C# itself, I did not know I already had a compiler.
Another update for visitors
https://stackoverflow.com/a/29963268/18573 is what I am now using, quite happily.
You can do it with an html object to retrieve the contents of the clipboard:
' Get clipboard text
Set objHTML = CreateObject("htmlfile")
text = objHTML.ParentWindow.ClipboardData.GetData("text")
EDIT: I use this snippet to put text back on the clipboard, but it needs third party software; a standalone executable 'clip.exe' which can be found on Windows 2003 Server or just on the internet:
' Do something with the text
text = replace(text, "you ", "you and your dog ")
' Put it back to the clipboard
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine text
oIn.Close
(Yes, it is all a little bit hackerdyhack)
VBScript doesn't support the clipboard. Most hosts that host vbscript, such as Internet Explorer give access through the host. Therefore vbscript running in IE or an HTA can use IE's clipboard support. The scripting hosts do not give clipboard support. You can use a vbs file to start IE through COM automation, navigate to a local page (to bypass security warnings), then use IE's clipboard.
Here's a code snippit (Outp. is a text stream)
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate2 "C:\Users\David Candy\Desktop\Filter.html"
Do
wscript.sleep 100
Loop until ie.document.readystate = "complete"
txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
ie.quit
If IsNull(txt) = true then
outp.writeline "No text on clipboard"
else
outp.writeline txt
End If
You need this function (is a little modification of this):
'TO CLEAR
ClipBoard("")
'TO SET
ClipBoard("Hello World!")
'TO GET
Result = ClipBoard(Null)
Function ClipBoard(input)
'#description: A quick way to set and get your clipboard.
'#author: Jeremy England (SimplyCoded)
If IsNull(input) Then
ClipBoard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text")
If IsNull(ClipBoard) Then ClipBoard = ""
Else
CreateObject("WScript.Shell").Run _
"mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _
& Replace(Replace(Replace(input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _
0,True
End If
End Function
For the equivalent of a "paste" operation I would run a command-line utility like ClipOut or paste, redirect output to a file and read the file contents.
return = WshShell.Run("cmd /c clipout.exe > output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("output.txt", 1)
text = file.ReadAll
file.Close
You can get ClipOut here: http://jasonfaulkner.com/ClipOut.aspx
You can get paste here: https://www.c3scripts.com/tutorials/msdos/paste.html
For the equivalent of a "copy" operation I would use the clip command line utility that actually comes with Windows and similar code as above.
About the clip utility: https://blogs.msdn.microsoft.com/oldnewthing/20091110-00/?p=16093

How to hide Windows Script Host window?

I started using today a program named "oblytile", which gives you the ability to add custom tiles to Metro UI in Windows 8/8.1. The program works fine, but I have one big issue when I open created tile to folder, program, file etc. for a short time a small black window (like CMD) pops up, like here:
and after the window disappears the program I wanted opens. I have watched some YouTube videos and other people didn't have something like this. I checked folder in which one program stores data about tiles and I found out that evry time I click on custom tile in Metro UI a VBScript is started.
Sample tile VBScript:
On Error Resume Next
Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strApp = "C:\Users\bluea_000\OneDrive"
arrPath = Split(strApp, "\")
For i = 0 to Ubound(arrPath) - 1
strAppPath = strAppPath & arrPath(i) & "\"
Next
objShell.CurrentDirectory = strAppPath
objShell.Run """C:\Users\bluea_000\OneDrive""" & ""
If Err.Number <> 0 Then
If InStr(1, strApp, "/") > 0 then
Else
If InStr(1, strApp, "www.") > 0 then
Else
If InStr(1, strApp, "shell:") > 0 then
Else
If objFSO.folderExists(strApp) Then
Else
If objFSO.FileExists(strApp) Then
Else
MsgBox strApp & " not found", 16, "OblyTile"
End If
End If
End If
End If
End If
Err.Clear
End If
Can anyone tell me how to hide this black window or fix it?
I asked on forum where the program was published, but probably the project has been abandoned and noone will answer me.
There are two interpreters for vbs files. Wscript and cscript.
Cscript is the command-line based scripting host and, thus, opens the black console window, wscript is the windows based scripting host and doesn't open a command-line window.
Use wscript for executing your script and no black window will pop up.
See https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/wsh_runfromwindowsbasedhost.mspx

Open a file with a .hta file [duplicate]

This question already has answers here:
Open a file with an HTA application
(2 answers)
Closed 2 years ago.
I'm making two HTA-applications. One is to install the other one. The code below is the VBScript in the installer HTA which does so that the computer recognises the .sjs extension (an extension which i've created and which has to do with the HTA being installed).
Public Sub Association(EXT, FileType, FileName, Icon)
Set b = CreateObject("wscript.shell")
b.regwrite "HKCR\" & EXT & "\", FileType
b.regwrite "HKCR\" & FileType & "\", "MY file"
b.regwrite "HKCR\" & FileType & "\DefaultIcon\", Icon
b.regwrite "HKCR\" & FileType & "\shell\open\command\", FileName & " %L"
b.regdelete "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" & EXT & "\Application"
b.regwrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" & EXT & "\Application", FileName
b.regdelete "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" & EXT & "\OpenWithList\"
b.regwrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" & EXT & "\OpenWithList\a", FileName
End Sub
Association ".sjs", "SJS file", "C:\Users\Donald\my_app.hta","C:\Users\Donald\Desktop\my_icon.ico"
I would like it to do so that when I open a .sjs file, it opens the file C:\Users\Donald\my_app.hta, but like this it opens a dialog box where it says "C:\Users\Donald\Documents\file.sjs isn't a valid Win32 application". How can I do so that it does as I want?
Using On Error Resume Next without error check is irresponsible.
[Dim ] xxx As Object isn't valid VBScript. (Should be: [Dim ] xxx As yyy to emphasize that all typed declarations are illegal in VBScript)
Fix that and try again. Use ftype and assoc to check the result of your registry manipulation.
On second thought:
I think that a .HTA file should/must be opened with mshta.exe. (Should have an "explicitly" somewhere; see below)
Update:
I use isql.hta to work with ADO Databases interactively. Parameters and statements are stored in .isql text files. So to tried to mimic your problem with: "I want .isql files associated with the isql.hta application; proof of success: doubleclick on .isql file opens isql.hta". So
assoc .isql=ISQLFile
.isql=ISQLFile
ftype ISQLFile="X:\pathto\isql.hta" %*
ISQLFile="X:\pathto\isql.hta" %*
Doubleclick =>
---------------------------
M:\lib\amfvbs0703\amsinc.isql
---------------------------
M:\lib\amfvbs0703\amsinc.isql is not a valid Win32 application.
---------------------------
OK
---------------------------
M: is a mapped drive; so Windows thinks it's enemy country.
ftype ISQLFile=c:\WINDOWS\system32\mshta.exe "X:\pathto\isql.hta" %*
ISQLFile=c:\WINDOWS\system32\mshta.exe "X:\pathto\isql.hta" %*
Doubleclick => SUCCESS

Output content of text file to computer voice via batch file

I have this batch file:
#echo off
echo StrText="Application created Successfully" > spk.vbs
echo set ObjVoice=CreateObject("SAPI.SpVoice") >> spk.vbs
echo ObjVoice.Speak StrText >> spk.vbs
start spk.vbs
This batch file creates spk.vbs in the same directory and outputs the text "Application created Successfully" with the computer voice.
Now I want the batch file to speak out the content of a text file given to it on the command line instead (%1). And the spk.vbs file should be created in the default Windows temporary directory instead. How can I do this?
***Edit 06.11.2012 20:24
Meanwhile I've discarded the idea of using a batch file script to generate a vbs script file and want to use the vbs script directly. Although I am an absolute beginner with VBS I created this one:
Set objFSO = CreateObject("Scripting.FileSystemObject")
strAFile = Wscript.Arguments(0)
Set objFile = objFSO.GetFile(strAFile)
If objFile.Size > 0 Then
Set objReadFile = objFSO.OpenTextFile(Wscript.Arguments(0), 1)
strContents = objReadFile.ReadAll
objReadFile.Close
set ObjVoice=CreateObject("SAPI.SpVoice")
ObjVoice.Speak strContents
Else
Wscript.Echo "The file is empty."
End If
It works, but probaly I've made a lot of mistakes. Can someone tell me how the vbs script can be optimized? Thank you!
***Edit 06.11.2012 22:19
After this worked a few times, now it does not work anymore: Now the computer speaker outputs only "Y" and the first character of the text file! Has this something to do with an error in my script?
***Edit 10.11.2012 19:32
Found the bug: The above script work only with ANSI-coded text-files. It does not work with UNICODE text-files! Why? How can I make it work with UNICODE text-files too?
Use the 4th parameter of the .OpenTextFile (or the 2nd parameter of the .OpenAsTextStream) method to specify whether to open the file as ASCII or Unicode (16).
I don't find any serious mistakes in your code snippet, but perhaps you want to consider:
using "Option Explicit" (explicitly)
checking whether the user passed at least one argument to the script
avoiding to refer to the same 'object' via different names/variables (strAFile, WScript.Arguments(0))
using .OpenAsTextStream as you have a File object already
avoiding 'magic numbers' (e.g. 1) by defining the appropriate constants (e.g. ForReading)
avoiding unnecessary variables (code you don't write can't be wrong)
E.g:
Set objReadFile = objFSO.OpenTextFile(WScript.Arguments(0), 1)
strContents = objReadFile.ReadAll
objReadFile.Close
==>
Const cnUnicode = -1
...
strContents = objFile.OpenAsTextStream(ForReading, cnUnicode).ReadAll()

Resources