[Library] GuiVar - Use Gui as Variable Between AHK Scripts

Post your working scripts, libraries and tools
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

[Library] GuiVar - Use Gui as Variable Between AHK Scripts

03 Apr 2014, 17:04

[Library] GuiVar

I needed one script to be able to share a variable with multiply other scripts.

Some ways this could be done are by saving the information to a file and then having all the scripts access that file.
Or it could possible be done with PostMessage but that is fairly complicated.
Or all the scripts could be Run by one shell script and then use environment variables.

But the method I decided to go with is to create a hidden Gui that acts like a variable. The name of the Gui is like the name of the variable and the text of the Gui being the content of the variable.

Code: Select all

;{ GuiVar
; Fanatic Guru
; 2014 11 06
; Version: 1.1
;
; LIBRARY that uses hidden Gui windows to pass information between scripts.
;
;---------------------------------------------------------------------------------
; GuiVar_Set				Set text content of a hidden Gui window
; GuiVar_Get				Get text content of a hidden Gui window
; GuiVar_List				Get name and text content of all hidden Gui window used by GuiVar
; GuiVar_Destroy			Destroy hidden Gui window used by GuiVar
; GuiVar_DestroySetTimer	Use SetTimer to check hidden Gui windows to destroy

; FUNCTIONS
;{-----------------------------------------------
;

; GuiVar_Set
; 
; Method:
;   GuiVar_Set(Variable Name, Value)
;
; Parameters:
;   1) {Variable Name} 	name base of Gui window in which to store Value
;   2) {Value}			text to store in Gui window
;
; Example:
;   GuiVar_Set("Customer","Fanatic Guru")
;
GuiVar_Set(Var,Value)
{
	DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
	if WinExist("GuiVar_" Var)
		ControlSetText,, %Value%, GuiVar_%Var%
	else
	{
		Gui, GuiVar_%Var%_GuiVar:Add, Text,, %Value%
		Gui, GuiVar_%Var%_GuiVar:Show, Hide, GuiVar_%Var%_GuiVar
	}
	DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
	return
}

; GuiVar_Get
; 
; Method:
;   GuiVar_Get(Variable Name)
;
; Parameters:
;   1) {Variable Name} name base of Gui window from which to get text
;
; Returns:
;   Text from Gui window
;
; Example:
;   Current_Customer := GuiVar_Get("Customer")
;
GuiVar_Get(Var)
{
	DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
	ControlGetText, Value,, GuiVar_%Var%_GuiVar
	DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
return Value
}

; GuiVar_List
;
; Method:
;   GuiVar_List(ByRef Array)
;
; Parameters:
;   1) {Array} 	variable in which to store Gui window data array
;
; Returns:
;   number of elements in data array
;
; ByRef:
;   Populates {Array} passed as parameter with Gui window data
;
GuiVar_List(ByRef Array)
{
	DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
	Array := {}
	WinGet, WinList, List, GuiVar_
	Loop, %WinList%
	{
		Hwnd := WinList%A_Index%
		WinGetTitle, WinTitle, ahk_id %Hwnd%
		ControlGetText, Value,, ahk_id %Hwnd%
		WinTitle := SubStr(WinTitle, 8, StrLen(WinTitle)-14)
		Array[WinTitle] := Value
	}
	DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
return WinList
}

; GuiVar_Destroy
; 
; Method:
;   GuiVar_Get(Variable Name)
;
; Parameters:
;   1) {Variable Name} 	name base of Gui window to destroy
;		default = "" 	destroys all Gui windows used by GuiVar
;
; Returns:
;   Number of Gui windows destroyed 
;
; Example:
;   GuiVar_Destroy("Customer")
;
; Note:	Only the script that first created a Gui can destroy that Gui
;
GuiVar_Destroy(Var := "")
{
	DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
	if Var
	{
		WinGet, WinList, ID, GuiVar_%Var%_GuiVar
		WinList ? WinList := 1 : WinList := 0
		Gui, GuiVar_%Var%_GuiVar:Destroy
	}
	else
	{
		WinGet, WinList, List, GuiVar_
		Loop, %WinList%
		{
			Hwnd := WinList%A_Index%
			WinGetTitle, WinTitle, ahk_id %Hwnd%
			Gui, %WinTitle%:Destroy
		}
	}
	DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
	return WinList
}

; GuiVar_DestroySetTimer
; 
; Method:
;   GuiVar_Get(Time, Value)
;
; Parameters:
;   1) 	{Time} 		time in ms to poll for Gui windows to destroy
;			default = 1000 	
;	2)	{Value}		destroy all Gui windows with this value
;			default = ""
;
; Returns:
;   None 
;
; Global:
;   Creates a global variable named [email protected]_DestroySetTimer
;
; Dependencies:
;	GuiVar_List, GuiVar_Destroy
;
; Example:
;   GuiVar_DestroySetTimer(10000, "Done") ; every 10 seconds destroy any GuiVar that equals "Done"
;
; Note:	Only the script that first created a Gui can destroy that Gui
;
GuiVar_DestroySetTimer(Time := 1000, Value := "")
{
	global [email protected]_DestroySetTimer := Value
	SetTimer, GuiVar_DestroySetTimer, %Time%
	return
	
	GuiVar_DestroySetTimer:
	GuiVar_List(List)
	for var, value in List
		if (value = [email protected]_DestroySetTimer)
			GuiVar_Destroy(Var)
	return
}
You need to run the GuiVar_Set Example script and while it is still running then run the GuiVar_Get Example script to get the data from the set script.

I have GuiVar in my lib folder but if you don't want to use it as a library you can just include the functions as needed in your scripts.

I am not sure what the ramifications are of trying to create 50 or 100 or 1000 hidden Gui windows are but for a reasonable number it seems to work fine. If I needed to pass something like a 1000 element array I would not create a 1000 different Gui windows though, I would convert the array to one string and then pass that one string through one GuiVar.

[Class] GuiVar
Here is a class version that is a little easier to use.

Code: Select all

;{ GuiVar
; Fanatic Guru
; 2017 11 16
; Version: 1.0
;
; CLASS that uses hidden Gui windows to pass information between scripts.
;
;---------------------------------------------------------------------------------
; 	Methods:
;		__New						Create new instance of Class
;
;		__Delete					Delete instance of Class and  Gui if possible
;
;		List							Get name and text content of all Gui windows used by GuiVar
; 											Parameters:
;												1) {Array} 	byref variable in which to store Gui window data array
;											Returns:
;   											number of elements in data array
;											Example:
;												Count := GuiVar.List(Arr)
;
;		Destroy					Destroy Gui 
;											Parameters:
;												1) {Variable Name} 		name base of Gui window to destroy
;													default = "" 	destroys all Gui windows used by GuiVar
;											Returns:
;												number of Gui windows destroyed 
;											Example:
;												GuiVar.Destroy("Customer")
;											Note:	Only the script that first created a Gui can destroy that Gui
;
;
;		Destroy_SetTimer		Use SetTimer to check hidden Gui windows to destroy
;											Parameters:
;												1) {Time}		time in ms to check for Gui windows to destroy
;													default = 1000 
;												2)	{Value}		destroy all Gui windows with this value
;													default = ""
;											Returns:
;												None 
;											Global:
;												Creates a global variable named [email protected]_Destroy_SetTimer
;											Dependencies:
;												GuiVar.List, GuiVar.Destroy
;											Example:
; 												GuiVar.Destroy_SetTimer(10000, "Done") ; every 10 seconds destroy any GuiVar that equals "Done"
; 											Note:	Only the script that first created a Gui can destroy that Gui
;
;	Properties:
;		Value						Text content of Gui
;											Example:
;												X := new GuiVar("SomeName")
;												X.Value := "Apple"
;												MsgBox % X.Value ; will display "Apple"
;
;		Name						Name used to title hidden Gui
;											Example:
;												MsgBox % X.Name ; from above example will display "SomeName"
;												X.Name := "AnotherName"
;												MsgBox % X.Name ; will display "SomeName"
;
;	Example Code:
;		Script1.ahk
; 			X := new GuiVar("Tree")
;			X.Value := "Apple
;		Script2.ahk
;			Y := new GuiVar("Tree") ; "Tree" must be same name used in script1.ahk to link GuiVar
;			MsgBox % Y.Value	; will display "Apple"
;}
class GuiVar
{
	__New(Var) 
	{
		this.Var := Var
	}
	__Delete() 
	{
		Var := this.Var
		DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
		WinGet, WinList, ID, GuiVar_%Var%_GuiVar
		WinList ? WinList := 1 : WinList := 0
		ControlSetText,,, % "GuiVar_"  this.Var
		try
			Gui, GuiVar_%Var%_GuiVar:Destroy
		DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
	}
	List(ByRef Array)
	{
		DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
		Array := {}
		WinGet, WinList, List, GuiVar_
		Loop, %WinList%
		{
			Hwnd := WinList%A_Index%
			WinGetTitle, WinTitle, ahk_id %Hwnd%
			ControlGetText, Value,, ahk_id %Hwnd%
			WinTitle := SubStr(WinTitle, 8, StrLen(WinTitle)-14)
			Array[WinTitle] := Value
		}
		DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
	return WinList
	}
	Destroy(Var := "")
	{
		DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
		if Var
		{
			WinGet, WinList, ID, GuiVar_%Var%_GuiVar
			WinList ? WinList := 1 : WinList := 0
			Gui, GuiVar_%Var%_GuiVar:Destroy
		}
		else
		{
			WinGet, WinList, List, GuiVar_
			Loop, %WinList%
			{
				Hwnd := WinList%A_Index%
				WinGetTitle, WinTitle, ahk_id %Hwnd%
				Gui, %WinTitle%:Destroy
			}
		}
		DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
		return WinList
	}
	Destroy_SetTimer(Time := 1000, Value := "")
	{
		global [email protected]_Destroy_SetTimer := Value
		SetTimer, GuiVar_Destroy_SetTimer, %Time%
		return
		
		GuiVar_Destroy_SetTimer:
		GuiVar.List(List)
		for var, value in List
			if (value = [email protected]_Destroy_SetTimer)
				GuiVar.Destroy(Var)
		return
	}
	Value
	{
		Get
		{
			DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
			ControlGetText, Value,, % "GuiVar_" this.Var "_GuiVar"
			DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
			return Value
		}
		Set
		{
			DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
			if WinExist("GuiVar_" this.Var)
				ControlSetText,, %Value%, % "GuiVar_"  this.Var
			else
			{
				Gui, % "GuiVar_" this.Var "_GuiVar:Add", Text,, %Value%
				Gui, % "GuiVar_" this.Var "_GuiVar:Show", Hide, % "GuiVar_" this.Var "_GuiVar"
			}
			DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
			return
		}
	}
	Name
	{
		Get
		{
			return this.Var
		}
		Set
		{
			DetectHiddenWindows, % (Setting_A_DetectHiddenWindows := A_DetectHiddenWindows) ? "On" :
			WinSetTitle, % "GuiVar_" this.Var "_GuiVar",, % "GuiVar_" Value "_GuiVar" 
			DetectHiddenWindows, %Setting_A_DetectHiddenWindows%
			this.Var := Value
		}
	}
}
FG
Last edited by FanaticGuru on 16 Nov 2017, 18:10, edited 2 times in total.
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 08:42

I am relatively new to ahk, but your script seems to be what I need to pass variables between scripts (currently I am using the clipboard). My problem is that I don't totally understand how tto use GuiVar. I have a script which gets a folder and creates a filename and puts them into a variable called destination. I want to pass that variable to another script to open the file I just created in the previous script.

Script that creates variable:

Code: Select all

; -----------------------------------------------------
; ----- This script performs the following actions ----
; -----                                            ----
; -----  1. Sets the title matching mode for a     ----
; -----     partial beginning string               ----
; -----  2. Checks for the existence of the        ----
; -----     outlook message window from pubmed,    ----
; -----     then activates that window             ----
; -----  3. Names the text file (with extension    ----
; -----     .txt) with today's date                ----
; -----  4. Uses Com objects to get body of        ----
; -----     currently selected email in outlook    ----
; -----  5. Reads file into variable Updateffile   ----
; -----  6. Gets part of file that starts with     ----
; -----     PMID                                   ----
; -----  7. Writes selected text out tp file after ----
; -----     deleting file first                    ----
; -----                                            ----
; -----------------------------------------------------
; -----                                            ----
; ----- This script was written by                 ----
; -----                 Thomas Zucker-Scharff      ----
; -----                                            ----
; -----------------------------------------------------
Return

#!s:: ; assign [Win]+[ALT]+s to run save text script
FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
Destination = %MyFolder%%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
SetTitleMatchMode,1 ; title must begin with String
IfWinExist, What's new for 'ccmembers' in PubMed - Message (HTML) ; has the message from pubmed been opened in outlook
{
   WinActivate
   ; ---------------------------------------------
   ; ---  get outlook text using com objects   ---
   ; ---------------------------------------------
   ; ***  This code thanks to Blackholyman on  ***
   ; ***  www.ahkscript.org forum              ***
   ; ---------------------------------------------
   oOutlook := ComObjActive("Outlook.Application")
   currentExplorer := oOutlook.ActiveExplorer
   Selection := currentExplorer.Selection
   currentMail := Selection.item(1)
   pubmedmail := currentmail.Body

   ; ----------------------------------------------
   ; ----- read file into variable and search -----
   ; ----------------------------------------------
   FileRead, UpdateFile, %Destination% ; read pubmed text file into variable UpdateFile
   StringLen, length, pubmedmail
   StringGetPos, PMIDPosition, pubmedmail, PMID
   ExtractedLength := (length - PMIDPosition)

   TextToWriteOut := SubStr(pubmedmail, PMIDPosition, length)
   FileDelete, %Destination%
   FileAppend, %TextToWriteOut%, %Destination%
}
run %Destination%
clipboard := Destination
; SendMessage, 0xC, 0, &Destination, ClassNN, WinTitle
Return

Script that I want to use destination variable in (instead of clipboard contents):

Code: Select all

; ------------------------------------------------------------------------------------------------------------------------------
; ----- This script performs the following actions, with user input                                                        -----
; -----                                                                                                                    -----
; -----     1. Sets the title matching mode for a partial beginning string                                                 -----
; -----     2. Checks for the existence of the window for EndNote X7 -, then activates that window                         -----
; -----     3. Lets user select a folder and file to import references from                                                -----
; -----     4. imports references from designated file (medline format)                                                    -----
; -----                                                                                                                    -----
; ------------------------------------------------------------------------------------------------------------------------------
; -----                                                                                                                    -----
; -----                                This script was written by Thomas Zucker-Scharff                                    -----
; -----                                                                                                                    -----
; ------------------------------------------------------------------------------------------------------------------------------
Return ; Stop the startup lines otherwise #i will run on startup

#!i:: ; [Win]+i to start script
SetTitleMatchMode,1 ; title must begin with String
IfWinExist,EndNote X7 -
{
   WinActivate
   Send !f ; access file menu
   Send i ; Import submenu
   Send {ENTER} ; select default of File
   Send +{TAB} ; access file name box
   msgbox, %clipboard%
   Send %clipboard% ; send text from Clipboard the file name and path (from savetextfromemail script)
   pause
   ; Send +{TAB 2} ; Shift and Tab twice to access Choose button
   ; Send {ENTER} ; 'click' choose button
   ; Send +{TAB 3} ; to get to folder selection
   ; SetTitleMatchMode, 1
   ; WinActivate, Open ; activate the open file window
   ; WinWait, Open ; wait until the user has selected a file and closed the open window
   ; WinWaitClose, Open ; wait until the user has selected a file and closed the open window
   Send {TAB}
   ; Send {TAB 2} ; to get to and select Import button
   Send {ENTER} ; Select to import file
   WinWait, Importing ; wait for program to complete the import process
   WinwaitClose, Importing ; continue processing after import closeses
   WinWait, Updating ; wait for program to complete the update process
   WinWaitClose, Updating ; continue processing after update process has finished
   Send {ENTER} ; select okay
}
So do I need to just enter the GuiVar_set command in the first as
GuiVar_set (Destination, %Destination%)

and then in the 2nd script

GuiVar_get (Destination)

or do I need to alter the GuiVar script first?
Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
Nextron
Posts: 1379
Joined: 01 Oct 2013, 08:23
Location: Netherlands OS: Win10 AHK: Unicode x32

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 09:36

That's out of the box thinking. Something similar was used before #If was implemented to make conditional hotkeys using #IfWinExists with custom windows.

How about implementing a GuiVar_Destroy that destroys the gui so system resources are freed (although this probably only works from the instance that created the gui)? Or something automatic, that destroys the gui once the text is emptied?
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 10:11

Why? I just want to pass a variable. I'm tempted to combine twi scripts and stop trying to make then more generic.
Tom Zucker-Scharff
An AutoHotKey Newbie
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 13:22

tzucker wrote:So do I need to just enter the GuiVar_set command in the first as
GuiVar_set (Destination, %Destination%)

and then in the 2nd script

GuiVar_get (Destination)

or do I need to alter the GuiVar script first?
You basically have it just some syntax problems:
GuiVar_set ("Destination", Destination) ; This put the value of the script variable Destination into a GuiVar named "Destination"

Destination := GuiVar_get ("Destination") ; This gets the value of a GuiVar named "Destination" and puts it in the script variable Destination

There is no need to alter the GuiVar functions in any way.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 13:45

Nextron wrote:That's out of the box thinking. Something similar was used before #If was implemented to make conditional hotkeys using #IfWinExists with custom windows.

How about implementing a GuiVar_Destroy that destroys the gui so system resources are freed (although this probably only works from the instance that created the gui)? Or something automatic, that destroys the gui once the text is emptied?
I can implement a GuiVar_Destroy although doing GuiVar_Set("Name","") should free up most of the resources but there will still be a phantom Gui window out there with no content.

Now that I think about it for a moment, I probably don't want to make the GuiVar be destroyed automatically even if it is empty because the user might want to have the GuiVar be null for some reason. Probably an implicit Destroy command is the best way to go.

It is important to realize that a GuiVar is like a Super-Duper Global Variable that can be used by many different AHK scripts all at the same time. There could be 20 scripts all doing Set and Get values to the same GuiVar as long as the script that initiated the GuiVar does not exit which will cause the GuiVar to be destroyed.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

31 Oct 2014, 14:53

An Example Script that shows how multiply scripts can all access and use the same GuiVar.

Code: Select all

; Test - GuiVar - Random
#SingleInstance off
Loop
{
	Random, X, 1, 10
	T := GuiVar_Get("TEST")
	if T
		NT := T + X
	else
		NT := X
	GuiVar_Set("TEST", NT)
	ToolTip, Script %A_ScriptHwnd% added %X% to TEST to make it %NT%
	Random, S, 1000, 10000
	Sleep S
}

Esc::ExitApp
If you run multiply instances of this same script, say three, each of the three running scripts will randomly every 1 to 10 seconds add 1 to 10 to a GuiVar named TEST and then display what it did with a tooltip.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
User avatar
BGM
Posts: 496
Joined: 20 Nov 2013, 20:56
GitHub: bgmCoder
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

01 Nov 2014, 10:17

There are other ways of passing variables, too.
You could use an ini file and just save the var there.

Or you could use a hidden window in one script and the other script can paste text into it and push it's submit button.

Or you could store a value in the registry (assuming you have admin access).
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

01 Nov 2014, 21:13

I'm currently trying to get GuiVar to work. For some reason it is paying the literal of the variable or nothing at all. When i execute the instructions by hand, they work, but with the script and GuiVar, to pass the variable of the path and filename, it just saves into the default directory with the default filename or the literal of the variable.
Tom Zucker-Scharff
An AutoHotKey Newbie
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

02 Nov 2014, 01:53

tzucker wrote:I'm currently trying to get GuiVar to work. For some reason it is paying the literal of the variable or nothing at all. When i execute the instructions by hand, they work, but with the script and GuiVar, to pass the variable of the path and filename, it just saves into the default directory with the default filename or the literal of the variable.
It is almost always a good idea to post your code that is not working if you are asking for help with why your code is not working.

From your generic description, I can give you the generic suggestion that it is important to get your syntax correct when writing code.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

02 Nov 2014, 15:01

Thanks
Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

03 Nov 2014, 09:39

The following is an annotated version of the script. I have started to separate the variable declarations for GuiVar from the rest of the script, so that the variable will be available to all scripts without having to run the first script. The script was working fine before I started trying to incorporate GuiVar. Now the Run %Description% line (near the end) is generating an error and the script is quiting (failed attempt to launch program or document Action: <R:\20141103_0935.txt> Params: <> Specifically the system cannot find the specified file. and indeed the file does not exist, but it was created before I tried altering the script. The clipboard method seemed to work better.

Code: Select all

; -----------------------------------------------------
; ----- This script performs the following actions ----
; -----                                            ----
; -----  1. Sets the title matching mode for a     ----
; -----     partial beginning string               ----
; -----  2. Checks for the existence of the        ----
; -----     outlook message window from pubmed,    ----
; -----     then activates that window             ----
; -----  3. Names the text file (with extension    ----
; -----     .txt) with today's date                ----
; -----  4. Uses Com objects to get body of        ----
; -----     currently selected email in outlook    ----
; -----  5. Reads file into variable Updateffile   ----
; -----  6. Gets part of file that starts with     ----
; -----     PMID                                   ----
; -----  7. Writes selected text out tp file after ----
; -----     deleting file first                    ----
; -----                                            ----
; -----------------------------------------------------
; -----                                            ----
; ----- This script was written by                 ----
; -----                 Thomas Zucker-Scharff      ----
; -----                                            ----
; -----------------------------------------------------
Return

#!s:: ; assign [Win]+[ALT]+s to run save text script
FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
basefilename = %MyFolder%%MyFile%
msgbox, The GuiVar variable is %basefilename%
Destination = %MyFolder%%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
msgbox, The destination variable is %destination%
; **************************************************************
; ***** GuiVar is a script by FanaticGuru of AHKScript.org *****
; **************************************************************
GuiVar_set ("basefilename", basefilename) ; Put value of basefilename variable into a GuiVar variable named basefilename
SetTitleMatchMode,1 ; title must begin with String
IfWinExist, What's new for 'ccmembers' in PubMed - Message (HTML) ; has the message from pubmed been opened in outlook
{
   WinActivate
   ; ---------------------------------------------
   ; ---  get outlook text using com objects   ---
   ; ---------------------------------------------
   ; ***  This code thanks to Blackholyman on  ***
   ; ***  www.ahkscript.org forum              ***
   ; ---------------------------------------------
   oOutlook := ComObjActive("Outlook.Application")
   currentExplorer := oOutlook.ActiveExplorer
   Selection := currentExplorer.Selection
   currentMail := Selection.item(1)
   pubmedmail := currentmail.Body

   ; ----------------------------------------------
   ; ----- read file into variable and search -----
   ; ----------------------------------------------
   FileRead, UpdateFile, %Destination% ; read pubmed text file into variable UpdateFile
   StringLen, length, pubmedmail
   StringGetPos, PMIDPosition, pubmedmail, PMID
   ExtractedLength := (length - PMIDPosition)

   TextToWriteOut := SubStr(pubmedmail, PMIDPosition, length)
   FileDelete, %Destination%
   FileAppend, %TextToWriteOut%, %Destination%
}
msgbox %Destination%
run %Destination%
clipboard := Destination
; SendMessage, 0xC, 0, &Destination, ClassNN, WinTitle
Return

Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

03 Nov 2014, 09:46

I just tested again with the same script and it seems to work only if the message window is open (I thought before it was working if the message was just selected). I will continue to try to separate my script into logical working parts.
Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

03 Nov 2014, 10:12

I changed the script to the following:

Script to set vars:

Code: Select all

; **************************************************************
; ***** Script to set path and File variables to be shared *****
; **************************************************************
#v:: ; assign [WIN}+v to start script
FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
basefilename = %MyFolder%%MyFile%
Destination = %MyFolder%%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
; **************************************************************
; ***** GuiVar is a script by FanaticGuru of AHKScript.org *****
; **************************************************************
GuiVar_set ("MyFolder", selectedfolder)
GuiVar_set ("MyFile", nowtext)
GuiVar_set ("basefilename", basefilename) ; Put value of basefilename variable into a GuiVar variable named basefilename
Script to use variables to create text file from outlook message:

Code: Select all

; -----------------------------------------------------
; ----- This script performs the following actions ----
; -----                                            ----
; -----  1. Sets the title matching mode for a     ----
; -----     partial beginning string               ----
; -----  2. Checks for the existence of the        ----
; -----     outlook message window from pubmed,    ----
; -----     then activates that window             ----
; -----  3. Names the text file (with extension    ----
; -----     .txt) with today's date                ----
; -----  4. Uses Com objects to get body of        ----
; -----     currently selected email in outlook    ----
; -----  5. Reads file into variable Updateffile   ----
; -----  6. Gets part of file that starts with     ----
; -----     PMID                                   ----
; -----  7. Writes selected text out tp file after ----
; -----     deleting file first                    ----
; -----                                            ----
; -----------------------------------------------------
; -----                                            ----
; ----- This script was written by                 ----
; -----                 Thomas Zucker-Scharff      ----
; -----                                            ----
; -----------------------------------------------------
Return

#!s:: ; assign [Win]+[ALT]+s to run save text script
; FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
; MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
; basefilename = %MyFolder%%MyFile%
; **************************************************************
; ***** GuiVar is a script by FanaticGuru of AHKScript.org *****
; **************************************************************
GuiVar_get (selectedfolder)
GuiVar_get (nowtext)
Destination := GuiVar_get ("basefilename").txt ; destination is the selected folder ":\" followed by today's date and time
msgbox, %Destination%
pause
SetTitleMatchMode,1 ; title must begin with String
IfWinExist, What's new for 'ccmembers' in PubMed - Message (HTML) ; has the message from pubmed been opened in outlook
{
   WinActivate
   ; ---------------------------------------------
   ; ---  get outlook text using com objects   ---
   ; ---------------------------------------------
   ; ***  This code thanks to Blackholyman on  ***
   ; ***  www.ahkscript.org forum              ***
   ; ---------------------------------------------
   oOutlook := ComObjActive("Outlook.Application")
   currentExplorer := oOutlook.ActiveExplorer
   Selection := currentExplorer.Selection
   currentMail := Selection.item(1)
   pubmedmail := currentmail.Body

   ; ----------------------------------------------
   ; ----- read file into variable and search -----
   ; ----------------------------------------------
   FileRead, UpdateFile, %Destination% ; read pubmed text file into variable UpdateFile
   StringLen, length, pubmedmail
   StringGetPos, PMIDPosition, pubmedmail, PMID
   ExtractedLength := (length - PMIDPosition)

   TextToWriteOut := SubStr(pubmedmail, PMIDPosition, length)
   FileDelete, %Destination%
   FileAppend, %TextToWriteOut%, %Destination%
}
msgbox %Destination%
run %Destination%
clipboard := Destination
; SendMessage, 0xC, 0, &Destination, ClassNN, WinTitle
Return

Script that does the same as the last one without using GuiVar and works (last one doesn't do anything now):

Code: Select all

; -----------------------------------------------------
; ----- This script performs the following actions ----
; -----                                            ----
; -----  1. Sets the title matching mode for a     ----
; -----     partial beginning string               ----
; -----  2. Checks for the existence of the        ----
; -----     outlook message window from pubmed,    ----
; -----     then activates that window             ----
; -----  3. Names the text file (with extension    ----
; -----     .txt) with today's date                ----
; -----  4. Uses Com objects to get body of
; -----     currently selected email in outlook    ----
; -----  5.
; -----                                            ----
; -----------------------------------------------------
; -----                                            ----
; ----- This script was written by
; -----                 Thomas Zucker-Scharff      ----
; -----                                            ----
; -----------------------------------------------------
Return

#s:: ; assign [Win]+s to run save text script
FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
Destination = %MyFolder%%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
SetTitleMatchMode,1 ; title must begin with String
IfWinExist, What's new for 'ccmembers' in PubMed - Message (HTML) ; has the message from pubmed been opened in outlook
{
   WinActivate
   ; ---------------------------------------------
   ; ---  get outlook text using com objects   ---
   ; ---------------------------------------------
   oOutlook := ComObjActive("Outlook.Application")
   currentExplorer := oOutlook.ActiveExplorer
   Selection := currentExplorer.Selection
   currentMail := Selection.item(1)
   pubmedmail := currentmail.Body

   ; ----------------------------------------------
   ; ----- read file into variable and search -----
   ; ----------------------------------------------
   FileRead, UpdateFile, %Destination% ; read pubmed text file into variable UpdateFile
   StringLen, length, pubmedmail
   StringGetPos, PMIDPosition, pubmedmail, PMID
   ExtractedLength := (length - PMIDPosition)

   TextToWriteOut := SubStr(pubmedmail, PMIDPosition, length)
   FileDelete, %Destination%
   FileAppend, %TextToWriteOut%, %Destination%
}
run %Destination%
Return
Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 10:11

So it turns out that I am somehow not using GuiVar correctly. I put in some msgbox commands to see what the output would look like and found there was no output from the GuiVar commands or almost none. Maybe I made a syntax error? Here is the code used to set the variables:

Code: Select all

; **************************************************************
; ***** Script to set path and File variables to be shared *****
; **************************************************************
#v:: ; assign [WIN}+v to start script
FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preffered destination folder
MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
basefilename = %MyFolder%%MyFile%
Destination = %MyFolder%%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
; **************************************************************
; ***** GuiVar is a script by FanaticGuru of AHKScript.org *****
; **************************************************************
GuiVar_set ("MyFolder", selectedfolder) ; this one and the next repeat in a different order so I could see if there was a problem there - neither work
GuiVar_set ("selectedfolder", MyFolder )
GuiVar_set ("MyFile", nowtext) ; this doesn't seem to do anything either
GuiVar_set ("basefilename", basefilename) ; Put value of basefilename variable into a GuiVar variable named basefilename - WORKS
GuiVar_set ("Destination", Destination) ; WORKS
msgbox, %selectedfolder% ; output is nothing
msgbox, %nowtext%, %MyFile% ; output is nothing, CORRECT
msgbox, %basefilename% ; WORKS
msgbox, %destination% ; WORKS
So what did I do wrong?

update:

When I add the following lines to another script:

Folder := GuiVar_get (selectedfolder)
Filebase := GuiVar_get (nowtext)
FilenameBase := GuiVar_get (basefilename)
Destination = %basefilename%.txt ; destination is the selected folder ":\" followed by today's date and time
msgbox, the variables from GuiVar are %Folder%, %Filebase%, and %Filenamebase%. Using the folder variable combined with the filename variable, we can generate the destination variable: %Destination%

the output of the variables is nothing but the .txt in destination.
Tom Zucker-Scharff
An AutoHotKey Newbie
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 12:48

tzucker wrote:So it turns out that I am somehow not using GuiVar correctly. I put in some msgbox commands to see what the output would look like and found there was no output from the GuiVar commands or almost none. Maybe I made a syntax error? Here is the code used to set the variables:

So what did I do wrong?

update:

When I add the following lines to another script:

Folder := GuiVar_get (selectedfolder)
Filebase := GuiVar_get (nowtext)
FilenameBase := GuiVar_get (basefilename)
Destination = %basefilename%.txt ; destination is the selected folder ":\" followed by today's date and time
msgbox, the variables from GuiVar are %Folder%, %Filebase%, and %Filenamebase%. Using the folder variable combined with the filename variable, we can generate the destination variable: %Destination%

the output of the variables is nothing but the .txt in destination.
I have not examined your code closely but right off the bat you cannot have a space between any function and its beginning (.

This is invalid, not just for GuiVar_Get but for all functions GuiVar_Get ("VariableName")
It must not have that space. It needs to be like this GuiVar_Get("VariableName")

It is also important to understand when you use "" and when you do not and what that means as well as when to use %% and when not.

Many people make many syntax errors involving when to use " and % and = or :=

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 13:29

Thanks - altering code now.
Tom Zucker-Scharff
An AutoHotKey Newbie
FanaticGuru
Posts: 1497
Joined: 30 Sep 2013, 22:25

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 15:26

Here is a working example similar to the your code:

Script One:

Code: Select all

; **************************************************************
; ***** Script to set path and File variables to be shared *****
; **************************************************************
#v:: ; assign [WIN}+v to start script
	FileSelectFolder, MyFolder,,6,Select a Destination Folder for the extracted message ; ask for preferred destination folder
	MyFile = %A_Year%%A_MM%%A_DD%_%A_Hour%%A_Min% ; variable contains yyyymmdd_hhmm
	basefilename = %MyFolder%\%MyFile%
	Destination = %MyFolder%\%MyFile%.txt ; destination is the selected folder ":\" followed by today's date and time
	; **************************************************************
	; ***** GuiVar is a script by FanaticGuru of AHKScript.org *****
	; **************************************************************
	GuiVar_Set("SelectedFolder", MyFolder)
	GuiVar_Set("NowText", MyFile)
	GuiVar_Set("BaseFileName", basefilename)
	GuiVar_Set("Destination", Destination)
return
Script Two

Code: Select all

#b::
	MyFolder := GuiVar_Get("SelectedFolder")
	MyFile := GuiVar_Get("NowText")
	BaseFileName := GuiVar_Get("BaseFileName")
	Destination := GuiVar_Get("Destination")
	MsgBox % "MyFolder`t`t = " MyFolder "`nMyFile `t`t = " MyFile "`nBaseFileName `t = " BaseFileName "`nDestination `t = " Destination
return
Run both scripts.
Hit Win+v which is the hotkey in the first script.
Pick your folder.
Hit Win+b which is the hotkey in the second script.
The second script will report the information saved to GuiVar by the first script.

This all assumes that you have GuiVar in your library folder so that its functions can be accessed as library functions. Other wise you will have to have the GuiVar functions in each script.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts

AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon

[Function] Timer - Create and Manage Timers
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 16:34

What is my library folder? I have GuiVar in the same folder with my scripts. I use AHK Startup to put them all together, GuiVar is one of the scripts that AHK Startup runs.
Tom Zucker-Scharff
An AutoHotKey Newbie
User avatar
tzucker
Posts: 42
Joined: 28 Oct 2014, 14:07
Location: Bronx, New York
Contact:

Re: [Library] GuiVar - Use Gui as Variable Between AHK Scrip

04 Nov 2014, 16:54

Maybe I don't know where to put the GuiVar file because whenever I load them all together now I get an error saying that the GuiVar Function does not exist. Where is this library folder?
Tom Zucker-Scharff
An AutoHotKey Newbie

Return to “Scripts and Functions”

Who is online

Users browsing this forum: No registered users and 25 guests