send a command to function to execute it

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Terka
Posts: 157
Joined: 05 Nov 2015, 04:59

send a command to function to execute it

30 Nov 2017, 09:21

if condition is met, i would like to run a command. i would like to use a function to do it.
can it be done?

Code: Select all

if_xy_execute(a,b,"run c:\notes.txt")
if_xy_execute()
{
        If (x = y)
        {
                  execute %command% ;		HERE HELP PLEASE EXECUTE THE COMMAND
        }
    Suspend,Off
    Return
}
User avatar
Delta Pythagorean
Posts: 627
Joined: 13 Feb 2017, 13:44
Location: Somewhere in the US
Contact:

Re: send a command to function to execute it

30 Nov 2017, 09:37

Code: Select all

if_xy_execute(a, b, "Run", "c:\notes.txt")

Run(File) {
	Run, % File
}

if_xy_execute(x, y, Func, Args*) {
	If (x = y) {
		If (IsFunc(Func))
			%Func%(Args*)
		Else If (IsLabel(Func))
			GoSub, % Func
		Else
			Return, False
	}
	Suspend, Off
	Return, True
}
Try this

[AHK]......: v2.0.12 | 64-bit
[OS].......: Windows 11 | 23H2 (OS Build: 22621.3296)
[GITHUB]...: github.com/DelPyth
[PAYPAL]...: paypal.me/DelPyth
[DISCORD]..: tophatcat

User avatar
Gio
Posts: 1247
Joined: 30 Sep 2013, 10:54
Location: Brazil

Re: send a command to function to execute it

30 Nov 2017, 09:40

Hello Terka.

A command cannot be run straight from text stored into a variable. That being said, there are a few ways to achieve the same effect. One of them is using AutoHotkey_H, to which you can pass written autohotkey commands and have them executed (i recommend this option if possible).
Another option is to have conditionals to "parse" the input string and than run the according commands (this option will require a lot of coding if you wish for many different commands to be possible).

Example (the code below is just an example, it is not a perfect parser!):

Code: Select all

if_xy_execute(5, 5, "run notepad.exe")
Return


if_xy_execute(x, y, command)
{
        If (x = y)
        {
                  StringSplit, command_, command, %A_Space%
                  if (command_1 = "run")
				{
					run %command_2%
				}
        }
    Suspend,Off
    Return
}
Best wishes.
Terka
Posts: 157
Joined: 05 Nov 2015, 04:59

Re: send a command to function to execute it

01 Dec 2017, 03:40

Hi all, thank you very much for your comments i will try your suggestions.
User avatar
noname
Posts: 516
Joined: 19 Nov 2013, 09:15

Re: send a command to function to execute it

01 Dec 2017, 05:37

A command cannot be run straight from text stored into a variable.
coco posted a solution some time ago, i tried it on win10 pro ahk 32bit and it still works.

Code: Select all

;  https://autohotkey.com/boards/viewtopic.php?t=5090

string_to_run:="run, notepad.exe"

ExecScript(string_to_run)

ExecScript(script, args:="", kwargs*)
{
	;// Set default values for options first
	child  := true ;// use WshShell.Exec(), otherwise .Run()
	, name := "AHK_" . A_TickCount
	, dir  := ""
	, ahk  := A_AhkPath
	, cp   := 0

	for i, kwarg in kwargs
		if ( option := SubStr(kwarg, 1, (i := InStr(kwarg, "="))-1) )
		; the RegEx check is not really needed but is done anyways to avoid
		; accidental override of internal local var(s)
		&& ( option ~= "i)^child|name|dir|ahk|cp$" )
			%option% := SubStr(kwarg, i+1)

	pipe := (run_file := FileExist(script)) || (name == "*") ? 0 : []
	Loop % pipe ? 2 : 0
	{
		;// Create named pipe(s), throw exception on failure
		if (( pipe[A_Index] := DllCall(
		(Join, Q C
			"CreateNamedPipe"            ; http://goo.gl/3aJQg7
			"Str",  "\\.\pipe\" . name   ; lpName
			"UInt", 2                    ; dwOpenMode = PIPE_ACCESS_OUTBOUND
			"UInt", 0                    ; dwPipeMode = PIPE_TYPE_BYTE
			"UInt", 255                  ; nMaxInstances
			"UInt", 0                    ; nOutBufferSize
			"UInt", 0                    ; nInBufferSize
			"Ptr",  0                    ; nDefaultTimeOut
			"Ptr",  0                    ; lpSecurityAttributes
		)) ) == -1) ; INVALID_HANDLE_VALUE
			throw Exception("ExecScript() - Failed to create named pipe", -1, A_LastError)
	}

	; Command = {ahk_exe} /ErrorStdOut /CP{codepage} {file}
	static fso := ComObjCreate("Scripting.FileSystemObject")
	static q := Chr(34) ;// quotes("), for v1.1 and v2.0-a compatibility
	cmd := Format("{4}{1}{4} /ErrorStdOut /CP{2} {4}{3}{4}"
	    , fso.GetAbsolutePathName(ahk)
	    , cp="UTF-8" ? 65001 : cp="UTF-16" ? 1200 : cp := Round(LTrim(cp, "CPcp"))
	    , pipe ? "\\.\pipe\" . name : run_file ? script : "*", q)
	
	; Process and append parameters to pass to the script
	for each, arg in args
	{
		i := 0
		while (i := InStr(arg, q,, i+1)) ;// escape '"' with '\'
			if (SubStr(arg, i-1, 1) != "\")
				arg := SubStr(arg, 1, i-1) . "\" . SubStr(arg, i++)
		cmd .= " " . (InStr(arg, " ") ? q . arg . q : arg)
	}

	if cwd := (dir != "" ? A_WorkingDir : "") ;// change working directory if needed
		SetWorkingDir %dir%

	static WshShell := ComObjCreate("WScript.Shell")
	exec := (child || name == "*") ? WshShell.Exec(cmd) : WshShell.Run(cmd)
	
	if cwd ;// restore working directory if altered above
		SetWorkingDir %cwd%
	
	if !pipe ;// file or stdin(*)
	{
		if !run_file ;// run stdin
			exec.StdIn.WriteLine(script), exec.StdIn.Close()
		return exec
	}

	DllCall("ConnectNamedPipe", "Ptr", pipe[1], "Ptr", 0) ;// http://goo.gl/pwTnxj
	DllCall("CloseHandle", "Ptr", pipe[1])
	DllCall("ConnectNamedPipe", "Ptr", pipe[2], "Ptr", 0)

	if !(f := FileOpen(pipe[2], "h", cp))
		return A_LastError
	f.Write(script) ;// write dynamic code into pipe
	f.Close(), DllCall("CloseHandle", "Ptr", pipe[2]) ;// close pipe

	return exec
}


Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: mikeyww and 155 guests