Изменение GUI в зависимости от времени Topic is solved

Помощь в написании скриптов
marusa122
Posts: 135
Joined: 22 Mar 2023, 07:48

Изменение GUI в зависимости от времени

12 Jan 2024, 01:26

Здравствуйте!
Есть фрагмент скрипта Autohotkey:

Code: Select all

Gui, New
Gui, Font, bold
FormatTime, OutputVar, , HH:mm
Gui, Add, Text,  , Доброе утро/день/вечер!
Gui, Add, Text,  , %A_Hour% : %A_Min% - текущее время
Gui, Show
Return
Нужно, чтобы скрипт определял текущее время на компьютере и вставлял его в GUI в формате ЧЧ:ММ
И в зависимости от времени менял текст выше:
- если время от 06:00 до 10:59 - "Доброе утро"
- если время от 11:00 до 16:59 - "Добрый день"
- если время от 17:00 до 21:00 - "Добрый вечер"
- если время другое - "Доброй ночи"

Как это реализовать? Скрипт может быть открыт целый день, время и текст в нем должны обновляться без перезапуска.
garry
Posts: 3771
Joined: 22 Dec 2013, 12:50

Re: Изменение GUI в зависимости от времени  Topic is solved

12 Jan 2024, 09:58

пример

Code: Select all

Gui,2: Font,Lucida Console s14 bold
ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
Gui,2: Add, Text,w400 vD1  , 
Gui,2: Add, Text,w400 vD2  , %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Gui,2: Show
SetTimer,A1,1000
gosub,a1
Return
;----
A1:
T:= A_Hour . A_Min
;ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
if ((T>=ac) and (T<=ad))           ;- if between 600-1059
 tx:="Доброе утро / good morning"
else if ((T>=ae) and (T<=af))      ;- if between 1100-1659
 tx:="Добрый день / good day"
else if ((T>=ag) and (T<=ah))      ;- if between 1700-2100
 tx:="Добрый вечер / good evening"
else 
 tx:="Доброй ночи / good night"
GuiControl,2:, D1,%tx%
;-
GuiControl,2:, D2, %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Return
;-----
2Guiclose:
Exitapp
;==========
20240113112948_screenshot.jpg
20240113112948_screenshot.jpg (18.67 KiB) Viewed 508 times

Code: Select all

#NoEnv                        ; Recommended for performance and compatibility with future AutoHotkey releases.
#Warn                         ; Enable warnings to assist with detecting common errors.
SendMode Input                ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%   ; Ensures a consistent starting directory.
#Singleinstance,force
;-
WA:=A_screenwidth,HA:=A_screenheight,xx:=100
Gui,2: -dpiscale +AlwaysOnTop -Caption +Border
Gui,2:Color,Black, 
Gui,2: Font,Lucida Console cYellow s14
ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
x:=(WA*1)/xx,y:=(ha*1)/xx,w:=(wa*8)/xx
Gui,2: Add, Text,x%x% y%y% w%w% vD1  , 
x:=(WA*9.5)/xx,y:=(ha*1)/xx,w:=(wa*20)/xx
Gui,2: Add, Text,x%x% y%y% w%w% vD2  ,
x:=(WA*0.5)/xx, y:=(ha*91)/xx,w:=(wa*29)/xx,h:=(ha*3.5)/xx   ;- GUI позиция x,y,w,h
Gui,2: Show,x%x% y%y% w%w% h%h%
SetTimer,A1,1000
gosub,a1
Return
;----
A1:
T:= A_Hour . A_Min
if ((T>=ac) and (T<=ad))           ;-  if between 600-1059
 tx:="Доброе утро"                 ;->   good morning
else if ((T>=ae) and (T<=af))      ;-  if between 1100-1659
 tx:="Добрый день"                 ;->   good day
else if ((T>=ag) and (T<=ah))      ;-  if between 1700-2100
 tx:="Добрый вечер"                ;->   good evening"
else                               ;-  else
 tx:="Доброй ночи"                 ;->   good night"
GuiControl,2:, D1,%tx% >
;-
FormatTime,ru,L0x419, dddd   MMM   MMMM     yyyy-MM-dd  HH:mm:ss
GuiControl,2:, D2,%ru%
Return
;-----
2Guiclose:
Exitapp
;-----------
esc::exitapp
;===========
marusa122
Posts: 135
Joined: 22 Mar 2023, 07:48

Re: Изменение GUI в зависимости от времени

17 Jan 2024, 01:40

@garry, как добавить этот код в другой GUI?
Мои попытки привели к тому, что время перестало обновляться без перезапуска...

Code: Select all

#SingleInstance, force
#NoEnv
SetWorkingDir %A_ScriptDir%

ProgramName := "Program1"

FileDelete,ListOfHotkeys.ini
FileAppend,
(
[Строка1]
Текст=Текст 1
Value=Some Value not needed
[Строка2]
Текст=Текст 2
Value=Some Value not needed
[Строка3]
Текст=Текст 3
Value=Some Value not needed
)
,ListOfHotkeys.ini
Gui, New
Gui, Font, bold
ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
Gui, Add, Text, w400 vD1 gP2 HwndField1Hwnd, 
Gui, Add, Text,w400 vD2 , %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Gui, Font, normal
Gui, Add, Text, W100 R1 , Поле для заметок:
Gui, Add, Button, W80 R0.75 vBt_Clear  gOnButtonClear , Очистить
Gui, Add, Edit , W300 R6,
Gui, Add, Listview, r6 w300 grid, Строка|Текст
IniRead, projects, ListOfHotkeys.ini
Loop, parse, projects, `n
{
    sect := A_LoopField
    IniRead, keys, ListOfHotkeys.ini, % sect
    IniRead, Текст, ListOfHotkeys.ini, % sect, Текст, %A_Space%
    LV_Add("", sect, Текст)
}
Loop, % LV_GetCount("Col")
    LV_ModifyCol(A_Index, "autoHdr w100")
LV_ModifyCol(1, "autoHdr w100")
LV_ModifyCol(2, "autoHdr w180")
AddToolTip(Field1Hwnd, "Приветствие программы")
Gui, Show, x1042 y444, %ProgramName%
SetTimer,A1,1000
gosub, A1
; Return - если это добавить, пропадает закрепление "всегда сверху"
WinWait, Program1 ahk_exe Program1.exe
WinSet, AlwaysOnTop, On
; WinWaitClose

Run, %A_ScriptDir%/Program2.exe

OnButtonClear:
    GuiControl,, Edit1,
    Return

Guiclose:
    Send {Esc}
    Exitapp
	
A1:
T:= A_Hour . A_Min
;ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
if ((T>=ac) and (T<=ad))           ;- if between 600-1059
 tx:="Доброе утро / good morning"
else if ((T>=ae) and (T<=af))      ;- if between 1100-1659
 tx:="Добрый день / good day"
else if ((T>=ag) and (T<=ah))      ;- if between 1700-2100
 tx:="Добрый вечер / good evening"
else 
 tx:="Доброй ночи / good night"
GuiControl,, D1,%tx%
GuiControl,, D2, %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Return

P2:
Run, "%A_ScriptDir%\Program2.exe"
Return

AddToolTip(_CtrlHwnd, _TipText, _Modify = 0)
{
	; Adds Multi-line ToolTips to any Gui Control
	; AHK basic, AHK ANSI, Unicode x86/x64 compatible
	;
	; Thanks Superfraggle & Art: http://www.autohotkey.com/forum/viewtopic.php?p=188241
	; Heavily modified by Rseding91 3/4/2014:
	; Version: 1.0
	;   * Fixed 64 bit support
	;   * Fixed multiple GUI support
	;   * Changed the _Modify parameter
	;           * blank/0/false:                                Create/update the tool tip.
	;           * -1:                                           Delete the tool tip.
	;           * any other value:                              Update an existing tool tip - same as blank/0/false
	;                                                            but skips unnecessary work if the tool tip already
	;                                                            exists - silently fails if it doesn't exist.
	;   * Added clean-up methods:
	;           * AddToolTip(YourGuiHwnd, "Destroy", -1):       Cleans up and erases the cached tool tip data created
	;                                                            for that GUI. Meant to be used in conjunction with
	;                                                            GUI, Destroy.
	;           * AddToolTip(YourGuiHwnd, "Remove All", -1):    Removes all tool tips from every control in the GUI.
	;                                                            Has the same effect as "Destroy" but first removes
	;                                                            every tool tip from every control. This is only used
	;                                                            when you want to remove every tool tip but not destroy
	;                                                            the entire GUI afterwords.
	;           * NOTE: Neither of the above are required if
	;                    your script is closing.
	;			
	; - 'Text' and 'Picture' Controls requires a g-label to be defined.
	; - 'ComboBox' = Drop-Down button + Edit (Get hWnd of the 'Edit'   control using "ControlGet" command).
	; - 'ListView' = ListView + Header       (Get hWnd of the 'Header' control using "ControlGet" command).
	Static TTHwnds, GuiHwnds, Ptr
	, LastGuiHwnd
	, LastTTHwnd
	, TTM_DELTOOLA := 1029
	, TTM_DELTOOLW := 1075
	, TTM_ADDTOOLA := 1028
	, TTM_ADDTOOLW := 1074
	, TTM_UPDATETIPTEXTA := 1036
	, TTM_UPDATETIPTEXTW := 1081
	, TTM_SETMAXTIPWIDTH := 1048
	, WS_POPUP := 0x80000000
	, BS_AUTOCHECKBOX = 0x3
	, CW_USEDEFAULT := 0x80000000
	
	Ptr := A_PtrSize ? "Ptr" : "UInt"
	
	
	; This is used to remove all tool tips from a given GUI and to clean up references used
	;  by those tool tips.
	;
	; This can be used if you want to remove every tool tip but not destroy the GUI
	;  and you don't know each individual control's Hwnd that has a tool tip.
	;
	; When a GUI is destroyed all Windows tool tip related data is cleaned up.
	;  The cached Hwnd's in this function will be removed automatically if the caching code
	;  ever matches them to a new GUI that doesn't actually own the Hwnd's.
	;
	; It's still possible that a new GUI could have the same Hwnd as a previously destroyed GUI
	;  with a child window that also has the same Hwnd as the previous destroyed GUIs tool tip window.
	;
	; If such an event occurred I have no idea what would happen. Either the tool tip
	;  wouldn't work, it may show something crazy or it may crash the script.
	;
	; To avoid that issue, do either of the following:
	;       * Don't destroy a GUI once created
	;       * Call AddToolTip(YourGuiHwnd, "Destroy", -1) directly before destroying the GUI
	;
	; NOTE: You do not need to do the above if you're exiting the script; Windows will clean up
	;  all tool tip related data and the cached Hwnd's in this function are lost when the script
	;  exits anyway.
	
	If (_TipText = "Destroy" Or _TipText = "Remove All" And _Modify = -1)
	{
		; Check if the GuiHwnd exists in the cache list of GuiHwnds
		; If it doesn't exist, no tool tips can exist for the GUI.
		;
		; If it does exist, find the cached TTHwnd for removal.
		Loop, Parse, GuiHwnds, |
			If (A_LoopField = _CtrlHwnd)
			{
				TTHwnd := A_Index
				, TTExists := True
				Loop, Parse, TTHwnds, |
					If (A_Index = TTHwnd)
						TTHwnd := A_LoopField
			}
		
		If (TTExists)
		{
			If (_TipText = "Remove All")
			{
				WinGet, ChildHwnds, ControlListHwnd, ahk_id %_CtrlHwnd%
			
				Loop, Parse, ChildHwnds, `n
					AddToolTip(A_LoopField, "", _Modify) ;Deletes the individual tooltip for a given control if it has one
				
				DllCall("DestroyWindow", Ptr, TTHwnd)
			}
			
			GuiHwnd := _CtrlHwnd
			; This sub removes 'GuiHwnd' and 'TTHwnd' from the cached list of Hwnds
			GoSub, RemoveCachedHwnd
		}
		
		Return
	}
	
	If (!GuiHwnd := DllCall("GetParent", Ptr, _CtrlHwnd, Ptr))
		Return "Invalid control Hwnd: """ _CtrlHwnd """. No parent GUI Hwnd found for control."
	
	; If this GUI is the same one as the potential previous one
	; else look through the list of previous GUIs this function
	; has operated on and find the existing TTHwnd if one exists.
	If (GuiHwnd = LastGuiHwnd)
		TTHwnd := LastTTHwnd
	Else
	{
		Loop, Parse, GuiHwnds, |
			If (A_LoopField = GuiHwnd)
			{
				TTHwnd := A_Index
				Loop, Parse, TTHwnds, |
					If (A_Index = TTHwnd)
						TTHwnd := A_LoopField
			}
	}
	
	; If the TTHwnd isn't owned by the controls parent it's not the correct window handle
	If (TTHwnd And GuiHwnd != DllCall("GetParent", Ptr, TTHwnd, Ptr))
	{
		GoSub, RemoveCachedHwnd
		TTHwnd := ""
	}
	
	; Create a new tooltip window for the control's GUI - only one needs to exist per GUI.
	; The TTHwnd's are cached for re-use in any subsequent calls to this function.
	If (!TTHwnd)
	{
		TTHwnd := DllCall("CreateWindowEx"
						, "UInt", 0                             ;dwExStyle
						, "Str", "TOOLTIPS_CLASS32"             ;lpClassName
						, "UInt", 0                             ;lpWindowName
						, "UInt", WS_POPUP | BS_AUTOCHECKBOX    ;dwStyle
						, "UInt", CW_USEDEFAULT                 ;x
						, "UInt", 0                             ;y
						, "UInt", 0                             ;nWidth
						, "UInt", 0                             ;nHeight
						, "UInt", GuiHwnd                       ;hWndParent
						, "UInt", 0                             ;hMenu
						, "UInt", 0                             ;hInstance
						, "UInt", 0)                            ;lpParam
		
		; TTM_SETWINDOWTHEME
		DllCall("uxtheme\SetWindowTheme"
					, Ptr, TTHwnd
					, Ptr, 0
					, Ptr, 0)
		
		; Record the TTHwnd and GuiHwnd for re-use in any subsequent calls.
		TTHwnds .= (TTHwnds ? "|" : "") TTHwnd
		, GuiHwnds .= (GuiHwnds ? "|" : "") GuiHwnd
	}
	
	; Record the last-used GUIHwnd and TTHwnd for re-use in any immediate future calls.
	LastGuiHwnd := GuiHwnd
	, LastTTHwnd := TTHwnd
	
	
	/*
		*TOOLINFO STRUCT*
		
		UINT        cbSize
		UINT        uFlags
		HWND        hwnd
		UINT_PTR    uId
		RECT        rect
		HINSTANCE   hinst
		LPTSTR      lpszText
		#if (_WIN32_IE >= 0x0300)
			LPARAM    lParam;
		#endif 
		#if (_WIN32_WINNT >= Ox0501)
			void      *lpReserved;
		#endif
	*/
	
	, TInfoSize := 4 + 4 + ((A_PtrSize ? A_PtrSize : 4) * 2) + (4 * 4) + ((A_PtrSize ? A_PtrSize : 4) * 4)
	, Offset := 0
	, Varsetcapacity(TInfo, TInfoSize, 0)
	, Numput(TInfoSize, TInfo, Offset, "UInt"), Offset += 4                         ; cbSize
	, Numput(1 | 16, TInfo, Offset, "UInt"), Offset += 4                            ; uFlags
	, Numput(GuiHwnd, TInfo, Offset, Ptr), Offset += A_PtrSize ? A_PtrSize : 4      ; hwnd
	, Numput(_CtrlHwnd, TInfo, Offset, Ptr), Offset += A_PtrSize ? A_PtrSize : 4    ; UINT_PTR
	, Offset += 16                                                                  ; RECT (not a pointer but the entire RECT)
	, Offset += A_PtrSize ? A_PtrSize : 4                                           ; hinst
	, Numput(&_TipText, TInfo, Offset, Ptr)                                         ; lpszText
	
	
	; The _Modify flag can be used to skip unnecessary removal and creation if
	; the caller follows usage properly but it won't hurt if used incorrectly.
	If (!_Modify Or _Modify = -1)
	{
		If (_Modify = -1)
		{
			; Removes a tool tip if it exists - silently fails if anything goes wrong.
			DllCall("SendMessage"
					, Ptr, TTHwnd
					, "UInt", A_IsUnicode ? TTM_DELTOOLW : TTM_DELTOOLA
					, Ptr, 0
					, Ptr, &TInfo)
			
			Return
		}
		
		; Adds a tool tip and assigns it to a control.
		DllCall("SendMessage"
				, Ptr, TTHwnd
				, "UInt", A_IsUnicode ? TTM_ADDTOOLW : TTM_ADDTOOLA
				, Ptr, 0
				, Ptr, &TInfo)
		
		; Sets the preferred wrap-around width for the tool tip.
		 DllCall("SendMessage"
				, Ptr, TTHwnd
				, "UInt", TTM_SETMAXTIPWIDTH
				, Ptr, 0
				, Ptr, A_ScreenWidth)
	}
	
	; Sets the text of a tool tip - silently fails if anything goes wrong.
	DllCall("SendMessage"
		, Ptr, TTHwnd
		, "UInt", A_IsUnicode ? TTM_UPDATETIPTEXTW : TTM_UPDATETIPTEXTA
		, Ptr, 0
		, Ptr, &TInfo)
	
	Return
	
	
	RemoveCachedHwnd:
		Loop, Parse, GuiHwnds, |
			NewGuiHwnds .= (A_LoopField = GuiHwnd ? "" : ((NewGuiHwnds = "" ? "" : "|") A_LoopField))
		
		Loop, Parse, TTHwnds, |
			NewTTHwnds .= (A_LoopField = TTHwnd ? "" : ((NewTTHwnds = "" ? "" : "|") A_LoopField))
		
		GuiHwnds := NewGuiHwnds
		, TTHwnds := NewTTHwnds
		, LastGuiHwnd := ""
		, LastTTHwnd := ""
	Return
}
garry
Posts: 3771
Joined: 22 Dec 2013, 12:50

Re: Изменение GUI в зависимости от времени

17 Jan 2024, 02:30

удалять > Gui, New

добавить RETURN после этого :
;..
Run, %A_ScriptDir%/Program2.exe
return
;-----------------
OnButtonClear:
;...


First part :

Code: Select all

#SingleInstance, force
#NoEnv
SetWorkingDir %A_ScriptDir%
ProgramName := "Program1"
F1:=a_scriptdir . "\test.ini"
ifexist,%f1%
  filedelete,%f1%
;--------------------  
ifnotexist,%f1%
 {
 Iniwrite,Текст 1,%f1%,Строка1,Текст
 Iniwrite,Value-1,%f1%,Строка1,Value
 Iniwrite,Текст 2,%f1%,Строка2,Текст
 Iniwrite,Value-2,%f1%,Строка2,Value
 Iniwrite,Текст 3,%f1%,Строка3,Текст
 Iniwrite,Value-3,%f1%,Строка3,Value
 }
;--------------------------- 
/* 
e:="
(
[Строка1]
Текст=Текст 1
Value=Some Value not needed
[Строка2]
Текст=Текст 2
Value=Some Value not needed
[Строка3]
Текст=Текст 3
Value=Some Value not needed
)"
Fileappend,%e%,%f1%,utf-8
e:=""
*/
;---------------------------

Gui, Font, bold
ac:=600,ad:=1059,ae:=1100,af:=1659,ag:=1700,ah:=2100
Gui, Add, Text, w400 vD1 gP2 HwndField1Hwnd, 
Gui, Add, Text,w400 vD2 , %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Gui, Font, normal
Gui, Add, Text, W100 R1 , Поле для заметок:
Gui, Add, Button, W80 R0.75 vBt_Clear  gOnButtonClear , Очистить
Gui, Add, Edit , W360 R6,TEST1`nTEST2
Gui, Add, Listview, r6 w360 grid Backgroundcfccc0, Строка|Текст|Value
;------------------------------------------------------------
;Fileread,command,*P65001 %F1%
Iniread,command,%F1%   ;- show only Строка1
Loop,Parse,Command,`n,`r
 {
 IniRead,Text,%f1%,% A_LoopField,Текст
 IniRead,Val ,%f1%,% A_LoopField,Value
 LV_Add("",A_LoopField,text,val)
 }
;Loop, % LV_GetCount("Col")
;    LV_ModifyCol(A_Index, "autoHdr w100")
LV_ModifyCol(1,100 ),LV_ModifyCol(2,120),LV_ModifyCol(3,120)

;AddToolTip(Field1Hwnd, "Приветствие программы")
Gui, Show, x1042 y444, %ProgramName%
SetTimer,A1,1000
gosub, A1
; Return - если это добавить, пропадает закрепление "всегда сверху"
WinWait, Program1 ahk_exe Program1.exe
WinSet, AlwaysOnTop, On
; WinWaitClose
;Run, %A_ScriptDir%/Program2.exe
;----------------------------------
OnButtonClear:
    GuiControl,, Edit1,
    Return
;----------------------------------
Guiclose:
;Send {Esc}
Exitapp
;----------------------------------
A1:
T:= A_Hour . A_Min
if ((T>=ac) and (T<=ad))           ;- if between 600-1059
 tx:="Доброе утро / good morning"
else if ((T>=ae) and (T<=af))      ;- if between 1100-1659
 tx:="Добрый день / good day"
else if ((T>=ag) and (T<=ah))      ;- if between 1700-2100
 tx:="Добрый вечер / good evening"
else 
 tx:="Доброй ночи / good night"
GuiControl,, D1,%tx%
GuiControl,, D2, %A_DDDD%  %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
Return
;----------------------------------
P2:
try,
Run,"%A_ScriptDir%\Program2.exe"
  catch,err 
    {
    x1:="Message=" . err.Message
    x2:="Extra  =" . err.extra
    x3:="File   =" . err.file
    x4:="Line   =" . err.line
    x5:="What   =" . err.what
    msgbox, 262208,ERROR,Error=`n%x1%`n----------------------`n%x2%`n%x3%`n%x4%`n%x5%`n--------------------`n
    return
    }
Return
marusa122
Posts: 135
Joined: 22 Mar 2023, 07:48

Re: Изменение GUI в зависимости от времени

18 Jan 2024, 02:49

Большое спасибо, теперь работает!

Return to “Помощь”

Who is online

Users browsing this forum: No registered users and 69 guests