AutoHotkey to use clipboard info to open files in Word works in Win8 but not in Win7 - macros

I created an AHK macro for a colleague. I have Windows 8; she has Windows 7. She has two "pending work" folders, one for documents and the other for audio files. The (text) file names in the documents folder correspond to the file names in the audio folder. So, for example, if there is an audio file called abc123.mp3 in the audio folder, there will be a file named abc123.txt in the documents folder.
As she opens the audio file in her transcription (media player) app, as part of that process, I want to have an AHK macro automatically open the matching text file (in Word).
I created an AHK macro that picks up from the point of her selecting the file to open from her transcription app. At the point where she selects the file, she invokes the AHK shortcut, which then toggles the rename feature (F2), copies the text to the clipboard (Ctrl+C), opens the file (Alt+O), and then uses the clipboard info (along with path info) to open the appropriate text file in Word.
It's working PERFECTLY on my system. However, when I logged into her system earlier today to demo the macros, the macro would not work. It works to a point - it will rename the file, copy the name of the file, and open the audio file, and file name is in the clipboard. But that's where it dies, with no error message. During troubleshooting, I tried isolating the macro down to one command - to simply open (fixed name) file in WinWord.exe, but that doesn't work, either.
I have been unable to find any research related to this issue. I know there are numerous ways to accomplish this task, but my AHK scripting skills and my free time are limited, so I went with what I knew I could accomplish quickly. I am open to suggestions for how to troubleshoot or tweak this macro to get it working on her system. It's hard to troubleshoot when it works on mine!
NumpadEnter::
Send {F2}{Sleep 100}
Clipboard=
Send ^c
Send {Sleep 100}!o{Sleep 100}
Run, WinWord.exe "C:\DocFiles\"%Clipboard%.txt
Return

Just a guess, but I believe you wanted Sleep command and not a Sleep Key? Be sure that you are using the Latest Version of AutoHotkey you can download it from www.ahkscript.org
NumpadEnter::
Send {F2}
Sleep, 100
Clipboard=
Send, ^c
Run, WinWord.exe "C:\DocFiles\"%Clipboard%.txt
Sleep 100
Send, ^o
Sleep 100
Send, ^v
Sleep 100
Send, !o
Return
Edit:
In the script you posted, you are telling the computer to Send a Sleep Key by placing brackets around the word Sleep. Like so {Sleep}
Furthermore, you are also telling your script to not just Send one key... you are telling it to Send the Sleep Key 100 times by placing the number 100 in the brackets, separated by a space, with the named key. Like so: {Sleep 100}
I fail to see how you would want to have your script simulate 100 Sleep key presses?
What I posted above uses the Sleep Command which delays the script in milliseconds. I believe this is truly what you want.

Related

programmatically press an enter key after starting .exe file in Matlab

In Matlab I can start external .exe files that sometime have a pop up that requires an enter key pressed. For example:
system('C:\Program Files (x86)\WinZip\WINZIP32.EXE')
will start Winzip, and then in order to use it you need to pass the "buy now" pop up window by pressing enter.
Now my problem is not with winzip, I only gave it as an example (i use winrar anyway :).
How can I programmatically press an enter key in Matlab in such cases ? (I use win 7)
Can an event listener be used to solve that?
EDIT: The java.awt.Robot class indeed works on explorer, but not on any software that has a pop up window with an OK button that needs to be pressed. I don't know why it doesn't work for that. I gave the winzip example because I assume everybody has winzip/winrar installed in their machine. The actual software I have is different and irrelevant for the question.
There is a way using Java from Matlab, specifically the java.awt.Robot class. See here.
Apparently there are two types of programs, regarding the way they work when called from Matlab with system('...'):
For some programs, Matlab waits until the program has finished before running the next statement. This happens for example with WinRAR (at least in my Windows 7 machine).
For other programs this doesn't happen, and Matlab proceeds with the next statement right after the external program has been started. An example of this type is explorer (the standard Windows file explorer).
Now, it is possible to return execution to Matlab immediately even for type 1 programs: just add & at the end of the string passed to system. This is standard in Linux Bash shell, and it also works in Windows, as discussed here.
So, you would proceed as follows:
robot = java.awt.Robot;
command = '"C:\Program Files (x86)\WinRAR\WinRAR"'; %// external program; full path
system([command ' &']); %// note: ' &' at the end
pause(5) %// allow some time for the external program to start
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); %// press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); %// release "enter" key
If your applications are only on Windows platform, you can try using .net objects.
The SendWait method of the SendKeys objects allows to send virtually any key, or key combination, to the application which has the focus, including the "modifier" keys like Alt, Shift, Ctrl etc ...
The first thing to do is to import the .net library, then the full syntax to send the ENTER key would be:
NET.addAssembly('System.Windows.Forms');
System.Windows.Forms.SendKeys.SendWait('{ENTER}'); %// send the key "ENTER"
If you only do it once the full syntax is OK. If you plan to make extensive use of the command, you can help yourself with an anonymous helper function.
A little example with notepad
%% // import the .NET assembly and define helper function
NET.addAssembly('System.Windows.Forms');
sendkey = #(strkey) System.Windows.Forms.SendKeys.SendWait(strkey) ;
%% // prepare a few things to send to the notepad
str1 = 'Hello World' ;
str2 = 'OMG ... my notepad is alive' ;
file2save = [pwd '\SelfSaveTest.txt'] ;
if exist(file2save,'file')==2 ; delete(file2save) ; end %// this is just in case you run the test multiple times.
%% // go for it
%// write a few things, save the file then close it.
system('notepad &') ; %// Start notepad, without matlab waiting for the return value
sendkey(str1) %// send a full string to the notepad
sendkey('{ENTER}'); %// send the {ENTER} key
sendkey(str2) %// send another full string to the notepad
sendkey('{! 3}'); %// note how you can REPEAT a key send instruction
sendkey('%(FA)'); %// Send key combination to open the "save as..." dialog
pause(1) %// little pause to make sure your hard drive is ready before continuing
sendkey(file2save); %// Send the name (full path) of the file to save to the dialog
sendkey('{ENTER}'); %// validate
pause(3) %// just wait a bit so you can see you file is now saved (check the titlebar of the notepad)
sendkey('%(FX)'); %// Bye bye ... close the Notepad
As explained in the Microsoft documentation the SendKeys class may have some timing issues sometimes so if you want to do complex manipulations (like Tab multiple times to change the button you actually want to press), you may have to introduce a pause in your Matlab calls to SendKeys.
Try without first, but don't forget you are managing a process from another without any synchronization between them, so timing all that can require a bit of trial and error before you get it right, at least for complex sequences (simple one should be straightforward).
In my case above for example I am running all my data from an external hard drive with an ECO function which puts it into standby, so when I called the "save as..." dialog, it takes time for it to display because the HDD has to wake up. If I didn't introduce the pause(1), sometimes the file path would be imcomplete (the first part of the path was send before the dialog had the focus).
Also, do not forget the & character when you execute the external program. All credit to Luis Mendo for highlighting it. (I tend to forget how important it is because I use it by default. I only omit it if I have to specifically wait for a return value from the program, otherwise I let it run on its own)
The special characters have a special code. Here are a few:
Shift +
Control (Ctrl) ^
Alt %
Tab {TAB}
Backspace {BACKSPACE}, {BS}, or {BKSP}
Validation {ENTER} or ~ (a tilde)
Ins Or Insert {INSERT} or {INS}
Delete {DELETE} or {DEL}
Text Navigation {HOME} {END} {PGDN} {PGUP}
Arrow Keys {UP} {RIGHT} {DOWN} {LEFT}
Escape {ESC}
Function Keys {F1} ... {F16}
Print Screen {PRTSC}
Break {BREAK}
The full list from Microsoft can be found here
There is a small javascript utility that simulates keystrokes like this on the Windows javascript interpreter.
Just create a js file with following code:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
then call it from Matlab after the necessary timeout like this:
system('c:\my\js\file\script.js {Enter}');
Can't test here now, but I think this should work...
If you need to run a console-only program in a context that permits full DOS redirection, you can create a file called, say, CR.txt containing a carriage return and use the '<' notation to pipe the value into the program.
This only works if you can provide all the keyboard input can be recorded in the file. It fails dismally if the input has to vary based on responses.
An alternative is to duplicate the input (and possibly output) stream(s) for the program and then pipe data into and out of the program. This is more robust and can permit dynamic responses to the data, but will also likely require substantial effort to implement a robot user to the application.
Rog-O-Matic is an example of a large application completely controlled by a program that monitors screen output and simulates keyboard input to play an early (1980s) ASCII graphic adventure game.
The other responses will be required for GUI-based applications.
Python package pywinauto can wait any dialog and click buttons automatically. But it's capable for native and some .NET applications only. You may have problems with pressing WPF button (maybe QT button is clickable - not checked), but in such case code like app.DialogTitle.wait('ready').set_focus(); app.DialogTitle.type_keys('{ENTER}') may help. Your case is quite simple and probably some tricks with pywinauto are enough. Is your "app with popup" 64-bit or 32-bit?
wait and wait_not functions have timeout parameter. But if you need precisely listener with potentially infinite loop awaiting popups, good direction is global Windows hooks (pyHook can listen mouse and keybd events, but cannot listen dialog opening). I'll try to find my prototype that can detect new windows. It uses UI Automation API event handlers... and... ops... it requires IronPython. I still don't know how to set UI Automation handler with COM interface from standard CPython.
EDIT (2019, January): new module win32hooks was implemented in pywinauto a while ago. Example of usage is here: examples/hook_and_listen.py.

AHK Sending a TXT file as typed out text

am using AHK to publish boilerplate e-mail body texts in our company. Our employees use various webmail, and other mail so managing templates is impossible. So comes AHK. We have created scripts to publish this with the details of the boilerplate within the body of the script, but it is difficult to delegate revision management when the script itself needs to be edited each time as the boilerplate text changes. Is there a way to send the contents of a Text file, i.e. "bp..pins.txt" as a keyboard input verses placing all the boilerplate text within the script?
Btw: We use Dropbox to sync scripts across users computers.
One way to do that is to simply use the command FileRead
FileSelectFile, path
::doit:: ; hotstring type "doit" to activate
FileRead, FileContent, %path%
Sendinput %FileContent%
return
Hope it helps
Do realize that SendInput has limitations. If you send enough text, it will buffer in the keyboard buffer and show up on the screen much slower than expected. It won't take more than a paragraph for the SendInput to end up being slower than a manual cut and paste.
I recommend reading the file into the clipboard and pasting it instead:
FileSelectFile, path
::doit:: ; hotstring type "doit" to activate
FileRead, FileContent, %path%
Clipboard := FileContent
SendInput ^v
return

Autohotkey daily macro doesn't work well

I created a macro in autohotkey that is able to copy at 7:40 a.m. the last file created in a shared disk into a dropbox folder. When I launch the macro to try it, setting the "time to meet" 2 minutes later for example, it works perfectly. The problem is that the day after the macro doesn't start. Could you help me please?
Thanks
Marco
SetTimer, Chronos, 59900
Return
Chronos:
FormatTime, TimeToMeet,,HHmm
If TimeToMeet = 740 ; If you wanted the script to start at 7 am put change 1006 to 700
{
run O:\research\
winactivate, research
sleep 1000
MouseClick, left, 289, 586
send {PgDn 6}
clipboard =
Send ^c
clipwait
sleep, 1000
FileCopy, %clipboard%,C:\Dropbox\
sleep 2000
winclose research
return
}
Return
Unattended user interface automation like this may not be the most reliable aproach.
I would recommend using the Windows Task Scheduler to handle launching the process. I think this might be safer than having the script running 24 / 7 waiting to go. Even more importantly, it looks like you are doing very basic file manipulation by automating the UI. This type of work may be better acomplished with a Windows batch file or Autohotkey's functions for files. Note that batch files are less fussy about screensavers and being logged in. I love AutoHotkey, but that seems to be a weak spot. Check out the documentation for each of the functions that start with the word file. I'd be surprised if you couldn't hook some of those up to do what you need. Since you seem to be looking for a file, check this one out:
http://www.autohotkey.com/docs/commands/LoopFile.htm
I think this thread may be of help as it finds the most recent file in a folder:
http://www.autohotkey.com/board/topic/57475-open-most-recent-file-date-created-in-a-folder/
Good luck!

Autohotkeys: Wait till the previous command is executed fully

What I am trying to do here is open an Excel sheet and do some copy paste here and there. I have created a script which will open the file and then start operations on it. Now I am using a slow computer so it takes time for excel file to open. Is it possible to somehow tell my autohotkey script that the file is opened and now u can start your shit. I know I can do it with sleep function but I was wondering if there is something better.
I would first check if Excel is running, then check if the specific file has been opened.
SetTitleMatchMode, 2
IfWinActive, Microsoft Excel
{
WinGetTitle, title, A
IfInString, title, specific file
{
Sleep, 1000 ; Just in case....
}
}
Actually, you are better of with a WinWait, specific file

Hotkey to restart autohotkey script?

Say I have an autohotkey script C:\path\to\my\script running. Is there a way to define a hotkey that re-starts it?
In order to prevent duplicate instances, I normally do not re-launch a script but use the build-in function Reload. I launch this with Ctrl+Win+Alt+R and use Ctrl+Win+Alt+E to edit the main AHK script.
^#!r::Reload
Actually, my script looks like this:
^#!r::
Send, ^s ; To save a changed script
Sleep, 300 ; give it time to save the script
Reload
Return
^!#e::Edit
As a matter of fact, all the way at the top of my script I have this to give me a visual and audio indication that the script was restarted:
#SingleInstance Force
#installKeybdHook
#Persistent
Menu, Tray, Icon , Shell32.dll, 25, 1
TrayTip, AutoHotKey, Started, 1
SoundBeep, 300, 150
Return
Make a hotkey that runs a script, which in this case is the same script and then exit.
somehotkey::
Run, C:\path\to\my\script.ahk
ExitApp
return
I found this to be the safest option of them all, because it takes care that the correct script is reloaded when you have multiple scripts running simultaneously, which was a recurring issue for me. The combination of the following also ensures that only one instance of a script will ever run at a time. The ScriptFullPath variable includes the name of the script.
#SingleInstance Force ;put this at the top of the script
^r::run, %A_ScriptFullPath%