How do I automate a right click in VBScript? - vbscript

I want to automate simulation of a right click to open the context menu. Once the menu is open, select the selected action/shortcut available.
I know how to open:
WshShell.SendKeys("+{F10}");
Or using the AutoIt automation language (BASIC like):
;--on right click event
MouseClick("right")
$count = 1
Do
Send("{DOWN}")
$count = $count + 1
Until $count > 7
Send("{ENTER}")
;---select shortcut
WinWaitActive("xxxxk")
;----doing execution from the 3rd program
ControlSend("xxxxx", "", "Edit2", "123ABC")
Sleep(500)
ControlSend("xxxxx", "", "Edit3", "123ABC")
Sleep(500)
Send("{ENTER}")
Sleep(500)
WinClose("xxxxx")
WinWaitActive("xxxxx", "Close")
Send("{ENTER}")
Can I have something like this in VBScript? Too messy, I think.

your answer is in your question
WshShell.SendKeys("+{F10}");
once the right click menu is open send another key 's' (in most cases 's' is used to select/select all)
shell.Sendkeys "s"
and you're done :)
here goes the complete code
shell.Sendkeys ("+{F10}")
shell.Sendkeys "s"
the above code should work in VBScript right click automation,
i'd also like to mention that Right-Click in a title bar is equivalent to ALT+SPACE, so if you want to right click on the title bar by vbscript i'll advice you to send ALT+SPACE instead
Source: http://msdn.microsoft.com/en-us/library/8c6yea83%28VS.85%29.aspx

Right click on what?
If you are talking about files/folders (in Windows Explorer), you can do it with shell automation: DoIt or InvokeVerb

Related

Send windows key in vbs?

I've looked everywhere for this, is it actually possible to do? If you press WIN + LEFT ARROW it will mount your selected window to the left of your screen, and that's exactly what I'm trying to do.
I have tried things like:
shl.sendkeys "#{LEFT}"
Because I found out that # could be for WIN just like + is for Shift and % is for Alt.
This may be a stupid question but it would help me out so much. Thank you for you time
Set Keys = CreateObject("WScript.Shell")
Keys.SendKeys("^{Esc}")
This should work, it Simulates the push of the Windows key by pushing the CTRL ^ and the ESC {Esc}keys, i don't know how to make the window mount to the left of the screen
VBScript's SendKeys doesn't support the Windows key.
You can use AutoIt instead:
Send("{#Left}")
Oh, so you want to mount the window to the left, I currently don't think there's a way to do that, but there's another shortcut for start menu, as well as windows key, it's Ctrl+Esc, ^{ESC}, you could possibly run the onscreen keyboard, then somehow tab over to the key, but it would be hard, also how about trying Alt+Space, %{SPACE}, to click the window icon then, M for move, then set the cursors position to the left of the screen, somehow? I don't currently need help moving the cursor in V.B.S., but you could Google it. Hash symbol is actually typing the symbol #, hash, tested with this. I also got help on the send-keys function, here. I have way to much researching, but I still can't find a answer. Some-one also said using "Auto hotkey", a third party program, but I don't really trust programs that can take control over your whole PC.
So I guess your options are:
Alt+Space to click window icon, then M for move, then move cursor to left side of the screen
Auto HotKey, although I don't recommend it.
Other commands, but SendKeys, in VBS,
Running a file, built in a different language to do so.
Or well, waiting-for / asking Microsoft to add it in, in the next version of Windows?!
a very late response, but here is my working effort
Dim shellObject : Set shellObject = CreateObject("WScript.Shell")
Extern.Declare micVoid, "keybd_event", "user32.dll", "keybd_event", micByte, micByte, micLong, micLong
Const KEYEVENTF_KEYUP = &H2
Const VK_LWIN = &H5B
Wait 5
Call Extern.keybd_event(VK_LWIN,0,0,0) 'press win key
Wait 5
shellObject.SendKeys "({UP})" 'right aline the window. TODO Error handlng
Wait 5
Call Extern.keybd_event(VK_LWIN,0,KEYEVENTF_KEYUP,0) 'up win key
Set shellObject = Nothing
try this
wshshell.sendkeys "{lwin}"

VS2010 Hotkey Name for Duplicating Line

In Visual Studio 2010 what is the hotkey binding name for duplicating a line in the keyboard editor? I want to change it from
CTRL + C / CTRL + V
to
CTRL + SHIFT + DOWN
Then I can be happy and content :)
This can be done by creating Macro. To create the macro, follow these steps.
Go to the macro explorer (Tools->Macros->Macro Explorer)
Right Click My Macros and click New Module.
In the module created copy and paste the code.
Sub DuplicateLine()
Dim line As String
DTE.ActiveDocument.Selection.StartOfLine(0)
DTE.ActiveDocument.Selection.EndOfLine(True)
line = DTE.ActiveDocument.Selection.Text
DTE.ActiveDocument.Selection.EndOfLine()
DTE.ActiveDocument.Selection.NewLine()
DTE.ActiveDocument.Selection.StartOfLine(0)
DTE.ActiveDocument.Selection.Text = line
End Sub
Now just assign a keyboard shortcut to it:
Go to Tools->Options
Under Environment, click Keyboard
In the "Show Commands Containing" textbox, enter "duplicate" (this according to the name you gave the module.)
Choose "Text Editor" from the "Use new shortcut in" list
Set focus in the "Press shortcut keys" textbox and hit the combination on the keyboard you wish to use for it (Ctrl+Shift+D in my case)
Hit the "Assign" button
Hit the OK button
*Source: * http://www.herrodius.com/blog/52

Need a "one-click" webdev hotkey workflow solution

Question for all you webdev guys/gals who have found a minimal-hassle development environment.
OS: Win7
Editor: JEdit
Task: Previewing work in a web browser
I would like to program a single hotkey to pack the following series of hotkeys into one. I use this sequence many times a day to preview my work in a browser.
The key commands are:
(from JEdit) ctrl + e ctrl + s [save all files]
(win) alt + tab [switch me over to browser]
(browser) ctrl + r [reload page]
I have not used Dreamweaver or flash in years but I remember punching f12 or ctrl + enter and having a browser pull up previewing the current work file. I am looking for a similar workflow but I cannot simply link to the saved file on disk. I need to look at the file through a local webserver. Typically I just have the browser open to the page I need and refresh it when I need to preview what I have done.
Another issue is the alt+tab step is not explicit enough. Often times the browser is not correctly sequenced in the open apps list to get to it without multiple tabs.
Thanks for any suggestions, workflow tips, etc.
Use this answer to create a command line method of refreshing a webpage ( it will work for any browser).
Next, create a baseline macro in JEdit for activating that script that you created:
In JEdit, you can record macros with Macros->Record Macro.
Do ctrl + e + s
Stop recording the macro with Macros->Stop Recording.
Open the JEdit browser tab with the newly created macro buffer that is now open in JEdit and add a system call at the end of it to run your visual basic script for refreshing the browser tab:
Runtime.getRuntime().exec("c:/PATH/TO/VB_SCRIPT AND ARGS IF YOU NEED THEM");
Save the macro.
Create a JEdit keyboard shortcut with utilities->global options, select "Shortcuts" then search for you macro and create a new keyboard binding.
Note that the Java beanshell exec command is non-blocking, so if you want to do anything else after executing the command, you may have to insert a sleep like:
Thread.currentThread().sleep(2000);
Just Press Alt + F5 and get it done!
To accomplish that, install AutoHotKey and run the script below (copy in a text file and change extension to .ahk). There is a portable version here. It was tested with AutoHotKey version is 1.0.48.05
This solution is pretty flexible since you can change Keys, Editors, Browsers and everything else. It works with Firefox and IE but you can easily customize.
The varTextEditor and varBrowsers where discovered using "WindowSpy" utility that comes bundled into AutoHotKey.
;###############################################################################
; Save all unsaved documents, refresh all opened browsers and return to text editor
;###############################################################################
!F5::
;Configuration vars. Edit here the settings of this script
; jEdit Eclipse
varTextEditor = SunAwtFrame,SWT_Window0
;varBrowsers = MozillaUIWindowClass,MozillaWindowClass,Chrome_WidgetWin_0,IEFrame,OpWindow,{1C03B488-D53B-4a81-97F8-754559640193}
; Firefox3 Firefox4 Chrome IEca Opera Safari
varBrowsers = MozillaWindowClass,IEFrame
;End of configuration vars.
WinGetClass, thisWindowClass, A ;Get the active window class
if (InStr(varTextEditor, thisWindowClass, true, 1) > 0) { ;true = case sensitive
varTextEditorClass = ahk_class %thisWindowClass%
if (thisWindowClass = "SunAwtFrame") {
OutputDebug, ...Saving everything
; SetKeyDelay, 100, 100, Play
Send ^+s ;Ctrl + Shift + S = Save all
} else if (thisWindowClass = "SWT_Window0") {
SendPlay ^s ;Ctrl + S = Save
}
Sleep, 500 ;Give some time to the data be recorded on hard disk
} else {
MsgBox, 0, Ops!, You must be in on these text editors: (%varTextEditor%) to get this script running, 5
return
}
;Refresh all opened (and maximized) browsers
Loop, parse, varBrowsers, `,
{
varClasseBrowser = ahk_class %A_LoopField%
if WinExist(varClasseBrowser) {
WinGet, winState, MinMax, %varClasseBrowser% ;get window state. -1 = minimized
if (winState != -1) {
WinActivate, %varClasseBrowser%
OutputDebug, ...Refresh browser %A_LoopField%
Send, {F5}
}
}
}
;Return to text editor
WinActivate, %varTextEditorClass%
return

Using AppActivate and Sendkeys in VBA shell command

I want to switch back and forth between application with the shell command in VBA.
I am using SendKeys to do stuff in process A then move to process B, then to process A then process B. It works fine for the first iteration. When I use AppActivate to go back to process B, it actually does switch focus back to process B. HOWEVER, it ignores subsequent commands from SendKeys.
Example code:
Sub pastePDF2TXT_v3(pdfName As String, txtName As String)
Dim acrobatID
Dim acrobatInvokeCmd As String
Dim acrobatLocation As String
Dim notepadID
Dim acrobatID2
Dim notepadID2
Debug.Print "here"
acrobatLocation = "C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Acrobat.exe"
acrobatInvokeCmd = acrobatLocation & " " & pdfName
acrobatID = Shell(acrobatInvokeCmd, 1)
AppActivate acrobatID
SendKeys "^a", True '^A selects everything already in the pdf file.
SendKeys "^c", True '^C copies the selection to the clipboard.
notepadID = Shell("NOTEPAD.EXE " & txtName, 1) ' invoke notepad on the text file.
AppActivate notepadID ' set the new app as teh active task.
SendKeys "^a", True '^A selects everything already in the text file.
SendKeys "^v", True '^V pastes the new stuff over the top of the old text file (deleting the old stuff)
SendKeys "%{END}", True ' makre sure last line of text file
SendKeys "{ENTER}", True
AppActivate acrobatID ' NOTE: APPEARS TO WORK UP TO THIS POINT.
SendKeys "{ENTER}", True ' NOTE: SECOND APP IGNORES SUBSEQUENT COMMANDS FROM HERE DOWN.
SendKeys "^a", True '^A selects everything already in the pdf file.
SendKeys "^c", True '^C copies the selection to the clipboard.
SendKeys "%f", True 'alt f, x to exit Notepad.exe
SendKeys "x", True
'acrobatID.Quit
Debug.Print "start second"
AppActivate notepadID ' set the new app as teh active task.
SendKeys "%{END}", True 'Go to end of text file.
SendKeys "^v", True '^V pastes the new stuff at end of file.
SendKeys "{ENTER}", True
SendKeys "^s", True
SendKeys "%f", True 'alt f, x to exit Notepad.exe
SendKeys "x", True
notepadID.Quit
acrobatID.Quit
End Sub
I know this question is old, but I have run into this same problem, but I don't think the answer that was chosen is the correct one.
When you call AppActivate, the script goes on halt, waiting for the target application to terminate. After the application is terminated, the script continues. I see no solution to this issue.
EDIT:
I use a batch-file to call CSCRIPT for the AppActivate command, and I notice you are strictly using a VBS file. Try calling CMD as a new window and pass CSCRIPT //NoLogo //B WScript.CreateObject("WSCript.shell").AppActivate("Window Name") as the argument, and see if that bypasses the issue.
Similarly, I was trying to use AppActivate on a pdf document I had opened with a shell command so that I could use SendKeys on it. It would always generate Run Time Error '5'. My solution, eventually was to NOT use AppActivate at all, in fact opening the document brings it to the forefront anyway. The problem is that the SendKeys statement executes immediately after the shell command but the pdf needs a second or two to open up. My solution is to pause the code for a couple seconds before excuting the sendkeys statement.
I used a time delay curtosy of pootle flump. Check out the thread here:
http://www.dbforums.com/microsoft-access/1219379-time-delay-vba.html
After hours of research on various forums, I could figure out that I wont be able to use Adobe library objects and functions with Adobe Reader. The only viable option left was to use Shell Commands to use "save as text" option available in the Adobe Reader's file menu. The shortcut key is Alt+f+a+x+s. I implemented these in the below code which worked perfectly, although I was required to insert delays in some steps.
Sub SavePDFasText()
Dim AdobeReaderPath As String
Dim PdfFilePath As String
Dim PDFid, NotepdId As Double
AdobeReaderPath = "C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe"
PdfFilePath = "D:\PowerGenMacro\opm_11.pdf"
PDFid = Shell(AdobeReaderPath & " " & PdfFilePath, vbNormalFocus)
Application.Wait TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 5)
'Alt+f+a+x is required to save the pdf as text in the adobe reader
SendKeys "%(FAX)", True
Application.Wait TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 2)
SendKeys "%S", True
SendKeys "^q", True
End Sub
This might be more of a comment than an answer, but I don't seem to be allowed to "comment", so...
It's amazing you've gotten as far as you did. Chances are, you're never going to be able to make this work reliably -- period. As soon as you do make it work, something will change about how the Acrobat UI behaves in a future release, or Windows will make another change to the rules for what things can send events to what other things, and then you're hosed again.
What you are probably running into in this case is Windows trying to prevent an application stealing the focus from another when a user is apparently busy interacting with the first one. You see the same kinds of problems trying to do things like have a button in one application write data to a temporary file and open MS Word to edit it. Windows prevents the focus from transferring away from the current app and over to MS Word because you just clicked a button in the current app.
So -- instead of trying to solve this impossible technical issue, let's take a step back and ask what you were originally hoping to accomplish by doing all of this. In that way, perhaps, we can get you where you're trying to go :)
Try
sendkeys "%{tab}"
to switch windows
but then keep only 2 active windows.
or try
appactivate only after sendkeys {Tab} so that text entry box is not selected before switchibg windows cmd.
or try
try appactivate window name, 1
then sleep 2000 °to allow time to bring that window into focus
You forgot to add "DoEvents" between each sendkeys and kind of delay/wait period, to give it some time to execute.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 5 years ago.
Improve this question
Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)?
The typical Shift+Insert does not seem to work here.
Yes.. but awkward. Link
alt + Space, e, k <-- for copy and
alt + Space, e, p <-- for paste.
I personally use a little AutoHotkey script to remap certain keyboard functions, for the console window (CMD) I use:
; Redefine only when the active window is a console window
#IfWinActive ahk_class ConsoleWindowClass
; Close Command Window with Ctrl+w
$^w::
WinGetTitle sTitle
If (InStr(sTitle, "-")=0) {
Send EXIT{Enter}
} else {
Send ^w
}
return
; Ctrl+up / Down to scroll command window back and forward
^Up::
Send {WheelUp}
return
^Down::
Send {WheelDown}
return
; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !{Space}ep
return
#IfWinActive
Not really programming related, but I found this on Google, there is not a direct keyboard shortcut, but makes it a little quicker.
To enable or disable QuickEdit mode:
Open the MS-DOS program, or the command prompt.
Right-click the title bar and press Properties.
Select the Options tab.
Check or un-check the QuickEdit Mode box.
Press OK.
In the Apply Properties To Shortcut dialog, select the Apply properties to current window only if you wish to change the QuickEdit setting for this session of this window only, or select Modify shortcut that started this window to change the QuickEdit setting for all future invocations of the command prompt, or MS-DOS program.
To Copy text when QuickEdit is enabled:
Click and drag the mouse pointer over the text you want.
Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.
To Paste text when QuickEdit is enabled:
Right-click anywhere in the window.
To Copy text when QuickEdit is disabled:
Right-click the title bar, press Edit on the menu, and press Mark.
Drag the mouse over the text you want to copy.
Press Enter (or right-click anywhere in the window) to copy the text to the clipboard.
To Paste text when QuickEdit is disabled:
Right-click the title bar, press Edit on the menu, and press Paste.
Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
The advantage of using SendInput is that
it doesn't rely on the command prompt system menu having an "Alt+Space E P" menu item to do the pasting (works for English and Spanish, but not for all languages).
it avoids that nasty flicker you get as the menu is created and destroyed.
Note, it's important to include the "{Raw}" in the SendInput command, in case the clipboard happens to contain "!", "+", "^" or "#".
Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!
There is also a great open source tool called clink, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.
On Windows 10, you can enable Ctrl + C and Ctrl + V to work in the command prompt:
Here's a free tool that will do it on Windows. I prefer it to a script as it's easy to set up. It runs as a fast native app, works on XP and up, has configuration settings that allow to remap copy/paste/selection keys for command windows:
Plus I know the developers.
simplest method is just the copy the text that you want to paste it in cmd and open cmd goto "properties"---> "option" tab----> check the (give tick mark) "quickEdit mode" and click "ok" .....now you can paste any text from clipboard by doing right click from ur mouse.
Thank you..
Thanks, Pablo, for referring to AutoHotkey utility.
Since I have Launchy installed which uses Alt+Space I had to modify it a but to add Shift key as shown:
; Paste in command window
^V::
; Spanish menu (Editar->Pegar, I suppose English version is the same, Edit->Paste)
Send !+{Space}ep
return
This is not really a shortcut but just a quick access to the control menu: Alt-space E P
If you can use your mouse, right click on the cmd window works as paste when I tried it.
Theoretically, the application in DOS Prompt has its own clipboard and shortcuts. To import text from Windows clipboard is "extra". However you can use Alt-Space to open system menu of Prompt window, then press E, P to select Edit, Paste menu. However, MS could provide shortcut using Win-key. There is no chance to be used in DOS application.
It took me a small while to figure out why your AutoHotkey script does not work with me:
; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return
In fact, it relies on keystrokes and consequently on keyboard layout!
So when you are, as I am, unfortunate to have only an AZERTY keyboard, your suggestion just does not work. And worse, I found no easy way to replace SendInput method or twist its environment to fix this. For example SendInput "1" just does not send digit 1.
I had to turn every character into its unicode to make it work on my computer:
#EscapeChar \
; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
clipboard3 := ""
Loop {
if (a_index>strlen(clipboard2))
break
char_asc := Asc(SubStr(clipboard2, a_Index, 1))
if (char_asc > 127 and char_asc < 256)
add_zero := "0"
else
add_zero := ""
clipboard3 := clipboard3 . "{Asc " . add_zero . char_asc . "}"
}
SendInput %clipboard3%
return
Not very simple...
If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.
I followed #PabloG's steps as follows
goto http://www.autohotkey.com/ - download autohotkey
follow simple installation steps
after installation create new *.ahk file as follows right click on desktop > new > Autohotkey Script > giveAnyFileName.ahk
right click on this file > Edit
copy paste autohotkey script given by #PabloG in his answer
save and close
double click on file to run
Done now you should be able to use Ctrl+v for paste in command prompt
You could try using Texter and create something unlikely like:
./p , triggered by space and replacing the text with %c
I just tested it and it works fine. The only gotcha is to use a rare sequence, as Texter cannot restrict this to just cmd.
There are probably other utilities of this kind which could work, and even AutoHotKey, upon which Texter is built could do it better, but Texter is easy :-)
A simpler way is to use windows powershell instead of cmd. itworks fine with texter.
I've recently found that command prompt has support for context menu via the right mouse click. You can find more details here: http://www.askdavetaylor.com/copy_paste_within_microsoft_windows_command_prompt.html
Pretty simple solution may be Console 2, redefine keys and you go.
If you're a Cygwin user, you can append the following to your ~/.bashrc file:
stty lnext ^q stop undef start undef
And the following to your ~/.inputrc file:
"\C-v": paste-from-clipboard
"\C-C": copy-to-clipboard
Restart your Cygwin terminal.
(Note, I've used an uppercase C for copy, since CTRL+c is assigned to the break function on most consoles. Season to taste.)
Source
Instead of "right click"....start your session (once you're in the command prompt window) by keying Alt/SpaceBar. That will open the Command Prompt window menu and you'll see your familiar, underlined keyboard command shortcuts, just like in Windows GUI.
Good luck!
Under VISTA Command prompt:
Click on the System Icon
Select Defaults from the Menu
On the Options tab in the Options group I have
"Quick Edit Mode", "Insert Mode", and "Auto Complete" selected
I think that "Quick Edit Mode" is what makes it work.
To paste whatever is in the Clipboard at the insertion point: Right Click.
To copy from the Command Window
Select by holding down the left mouse button and dragging the pointer across what you want to copy
Once selected, right click
To paste at the insertion point, right click again.

Resources