What's the difference between Run command and commands in cmd? - autohotkey

I have the following script:
^!c::
Run stop
Return
Stop is configured to run a program via environment variables.
So if I open up cmd and type “stop” and hit enter the program opens as intended, even if I push winkey + R it does the same thing. However if I use the script with ctrl+alt+c. I do not get the same result.
Why is the script doing something different?
How can I change my script to behave the same way as if it was typed into cmd or winkey + R?

Simple:
run, %comspec% /c stop
Or if this doesn't work you could just start a cmd window and send it directly
run, %comspec% /k
WinWait, %comspec%
WinActivate
Send stop{Enter}
/c tells the console window to close after execution, /k lets it stay open
or you could use an COM object and even get the output.
objShell := ComObjCreate("WScript.Shell")
objExec := objShell.Exec(ComSpec " /c stop")
strStdOut := ""
while, !objExec.StdOut.AtEndOfStream
{
strStdOut := objExec.StdOut.ReadAll()
}
Update:
Without the run command at all:
SetTitleMatchMode, 2
send #r
WinWait, TITLE_OF_THE_RUN_WINDOW
WinActivate
send cmd{Enter}
WinWait, cmd.exe
WinActivate
WinGetTitle, title
Send stop{Enter}
WinWait, %title%,,, stop
WinClose,
TITLE_OF_THE_RUN_WINDOW replace this with the title of the window, which opens on Win+r. A windows cmd window has the command in its title while it gets executed. So we save the title of the command window, and wait for it to drop the command ("stop") and close it then.
UPDATE: Cmd window close added to solution 4

Related

Powershell script with response and no window?

I want to run a command in PowerShell and use the response in AutoHotkey. I have found a lot of information on how to run a PowerShell script, but none saying how I can use the response from it in AutoHotkey.
I have tried this:
MsgBox % ComObjCreate("WScript.Shell").Exec("powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -noProfile -nologo dir").StdOut.ReadAll()
But this still flashes a window for a very brief time. I loop this command for every 25ms, so letting a window blink that often is not a valid solution.
Edit:
Ended up with this as the simplest solution:
cmd = powershell.exe -command "(Get-Process -Id " %pid% ").Threads[1].WaitReason"
shell := setup()
Loop {
string := shell.exec(cmd).stdout.readall()
...}
setup() {
detecthiddenwindows on
run %comspec% /k ,, hide useerrorlevel, pid
winwait ahk_pid %pid%,, 10
DllCall("AttachConsole", "uint", pid)
con := DllCall("CreateFile"
, "str", "CONOUT$", "uint", 0xC0000000, "uint", 7, "uint", 0, "uint", 3, "uint", 0, "uint", 0)
oshell := comobjcreate("wscript.shell")
return oshell
}
Note: Using AHK (AutoHotkey) with an external PowerShell process is ill-suited to a task that must run every 25ms, as you've discovered yourself - there's too much processing overhead.
If getting a directory listing is all that is needed, you can do that with built-in AHK features, using the Loop command for files - see this answer.
The solution below generally demonstrates how to run a console program:
hidden (no flashing windows)
synchronously (wait for it exit)
with its output captured
from AHK.
You can't use ComObjCreate("WScript.Shell").Exec() to run a console application hidden.
Conversely, while you can use RunWait to run hidden, you cannot use it to capture (console) output.
The workaround is to:
Use RunWait.
Add an output redirection to a (temporary) file to your console-program invocation.
Read that file's content with FileRead afterwards (and delete the temp. file).
; Get a temporary file path
tempFile := A_Temp "\" DllCall("GetCurrentProcessId") ".txt" ; "
; Run the console program hidden, redirecting its output to
; the temp. file (with a program other than powershell.exe or cmd.exe,
; prepend %ComSpec% /c; use 2> to redirect error output), and wait for it to exit.
RunWait, powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -noProfile dir > %tempFile%,, Hide
; Read the temp file into a variable and then delete it.
FileRead, content, %tempFile%
FileDelete, %tempFile%
; Display the result.
MsgBox % content

How to add administrator privileges to AutoHotkey script?

I compiled it to an executable, but to open it I have to right-click and press "Run as administrator". I want it to request admin privileges each time I run it, but how to do it?
I can't do this:
Because then it doesn't work when I copy it to a second computer.
Try adding this to the auto-execute section (top of the script):
; If the script is not elevated, relaunch as administrator and kill current instance:
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
try ; leads to having the script re-launching itself as administrator
{
if A_IsCompiled
Run *RunAs "%A_ScriptFullPath%" /restart
else
Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
}
ExitApp
}
and recompile the script.
For more details read https://autohotkey.com/docs/commands/Run.htm#RunAs.
Here's a much simpler code for this purpose:
#SingleInstance Force
if not A_IsAdmin
Run *RunAs "%A_ScriptFullPath%"
It will run the script as Admin if it's not already running as Admin.
If you don't have #SingleInstance Force on top of your script, it will ask that if you want to replace the running script (not admin) with admin. So to prevent that, add the mentioned line on top of your script.
If you might compile your script in the future, it's better to use this one instead to make it future-proof:
#SingleInstance Force
if !A_IsAdmin
Run, % "*RunAs " (A_IsCompiled ? "" : A_AhkPath " ") Chr(34) A_ScriptFullPath Chr(34)
Chr(34) returns character "
Source: https://www.autohotkey.com/boards/viewtopic.php?t=39647

How to write a script that creates hotkeys?

I have a lot of little hot keys defined, such as:
; Open CMD
#c::
Run, cmd.exe
WinWait, ahk_exe cmd.exe
WinActivate
Return
I'd like to build a function that takes the exe and hot key, and it will bind the app with that hot key. Here's what I have so far:
bind_exe_to_hotkey(exe,hotkey)
{
run_label:
Run, %exe%
WinWait, ahk %exe%
WinActivate
Return
HotKey, %hotkey%, run_label
}
bind_exe_to_hotkey("cmd.exe","#c")
However, this just opens a command window. What am I doing wrong? Is there an easier/better way to accomplish this?
Binds key to a function that handles launching an executable:
#c: launch("cmd.exe")
#n: launch("notepad.exe")
launch(exe)
{
Run, %exe%
WinWait, ahk %exe%
WinActivate
}

AutoHotKey run command in background

I'm trying to run a command with AutoHotKey that I would normally run with cmd.exe. Here is the command:
pandoc -s "C:\input.txt" -o "D:\output.html"
This is how I do it in AutoHotKey:
#a::
run pandoc -s "C:\input.txt" -o "D:\output.html"
return
The only problem is that this opens up the a command prompt called "pandoc". Normally I'd just type in the command in cmd.exe and it would run without any hiccups or any windows opening. For this, however, that pandoc window shows up. Am I doing it correctly? Is there any easy way to suppress the window and run the command in the background?
Runs a program without opening a window. The program is "cmd.exe", the windows command shell. It is invoked with arguments "/c time /t", which outputs the current time. It redirects the output to "c:\t.txt"
program
#a::
run cmd /c time /t > c:\t.txt, c:\, hide
return
output
c:\>type c:\t.txt
14:28

create shortcut in cmd prompt using autohotkey

I am using python and virutal environment in windows7. Every time I need to go to the project folder, shift+right click to open command prompt and activate virtualenv.
Instead I can hit win+R them type cmd to open a command prompt.
Then type
C:\cd D:\path\to\project
D:
workon projectEnvironment
Can this be done to create a shortchut like 'work' from autohotkey ??
Your windows-R shortcut would work like this:
Start a cmd window and wait until it is active.
Then begin to send your commands.
#r::
Run, %comspec% /c cmd.exe
SetTitleMatchMode, 2
WinWaitActive, cmd.exe
SendInput, cd D:\projects\folder{enter}
SendInput, D:{enter}
SendInput, workon projectEnvironment{enter}
return
Although I was unable to create shortcut key combination in cmd, I created a shortcut key, i.e. windows button + space
#space::Send cd D:\projects\folder{enter} D:{enter} workon projectEnvironment {enter}
Edit
here's the real solution
::work::cd D:\projects\folder{enter} D:{enter} workon projectEnvironment {enter}
After an hour of researching why my script would write " instead of \ when Sending a path in cmd prompt, I realized that sometimes the cmd prompt will interpret some keys differently for AutoHotkey.
I used to write Send, cd C:\File\Path {Enter} and it returned:
C:"File"Path
You can use ASC codes for / = {ASC 47} and \ = {ASC 92}, which in the end you write:
Send, cd C:{ASC 92}File{ASC 92}Path {Enter}