<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AHK: GUI HTML интерфейс (шаблон для Вашего проекта)]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=12598&amp;type=atom" />
	<updated>2017-04-07T09:45:36Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=12598</id>
		<entry>
			<title type="html"><![CDATA[AHK: GUI HTML интерфейс (шаблон для Вашего проекта)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=114757#p114757" />
			<content type="html"><![CDATA[<p>Скрипт является примером использования HTML для построения GUI интерфейса.<br />Приведены примеры организации типового взаимодействия между AHK и DOM структурой HTML документа.<br />Надеюсь, пригодится как шаблон для ваших разработок.</p><div class="codebox"><pre><code>
; Для для включения html в exe-шник можно использовать модифицированный Ahk2Exe
; https://autohotkey.com/boards/viewtopic.php?f=24&amp;t=521
; http://fincs.ahk4.net/files/NewAhk2Exe-preview2a.zip
;@Ahk2Exe-AddResource interface.html

#Warn
#NoEnv
#SingleInstance Force
SetBatchLines -1
; Gui, -DPIScale   - не использовать! (Будут проблемы с масштабированием html содержимого)

Gui, Add, GroupBox,            w476 h90                , % &quot;AHK Application&quot;
Gui, Add, Button,  xp14  yp+20 w90          gGetFromIE , % &quot;Get from IE&quot;
Gui, Add, Edit,    x+14  yp    w240        vAHKEditBox , % &quot;test AHK string&quot;
Gui, Add, Button,  x+14  yp    w90           gSendToIE , % &quot;Send to IE&quot;
Gui, Add, Button,  xs+14 y+8   w160    gCallJavaScript , % &quot;Call JavaScript Function&quot;
Gui, Add, ActiveX, x0    y+32  w500 h84 hwndIEhwnd vIE , Shell.Explorer
htmlfile := A_IsCompiled ? &quot;res://&quot; A_ScriptFullPath &quot;/interface.html&quot; : A_ScriptDir &quot;\interface.html&quot;
IE.Navigate(htmlfile)
; loop { ; Ожидание загрузки html - (приводится во всех примерах, но нам для локальной страницы абсолютно ничего не дает)
; 	If !IE.busy
; 		break
; }
Gui, Color, cC0C0C0
; Gui, Show, w500 h188, % &quot;ActiveX Shell.Explorer&quot;
Gui, Show, w500 h190, % &quot;ActiveX Shell.Explorer&quot;

loop { ; Ожидание инициализации подключений (вот эта задержка - обязательна!)
	Try {
		IE.document.All.IEInputBox
		break
	}
}

; Подключение к html элементу IEInputBox
IEInpBox := IE.document.GetElementById[&quot;IEInputBox&quot;]
; IEInpBox := IE.document.All.IEInputBox ; альтернативный способ

Events := [] ; Подключение к событиям html элементов INPUT (для всех элементов используйте &quot;*&quot;)
Inputs := IE.document.GetElementsByTagName[&quot;input&quot;]
Loop % Inputs.length {
	Events[A_Index] := Inputs[A_Index-1]
	ComObjConnect(Events[A_Index], Inputs[A_Index-1].id &quot;_&quot;)
}
return

; Нажатие на кнопку &quot;Get from IE&quot;
GetFromIE:
	x := IEInpBox.value
	GuiControl,, AHKEditBox, % x
return

; Нажатие на кнопку &quot;Send to IE&quot;
SendToIE:
	GuiControlGet, y,, AHKEditBox
	IEInpBox.value := y
return

; Нажатие на кнопку &quot;Call JavaScript Function&quot;
CallJavaScript:
	GuiControlGet, param,, AHKEditBox
	IE.document.parentWindow.execScript(&quot;tempJsVar=funcTest(&#039;&quot; param &quot;&#039;)&quot;)
	ret := IE.document.Script.tempJsVar
	GuiControl,, AHKEditBox, % ret
return

; Нажатие на кнопку &quot;Get from AHK&quot;
IEButtonGet_OnClick(this) {
	GuiControlGet, v,, AHKEditBox
	this.document.GetElementById[&quot;IEInputBox&quot;].value := v
}

; Нажатие на кнопку &quot;Send to AHK&quot;
IEButtonSend_OnClick(this) {
	v := this.document.GetElementById[&quot;IEInputBox&quot;].value
	GuiControl,, AHKEditBox, % v
}

GuiEscape:
GuiClose: 
	Gui, Destroy
ExitApp
</code></pre></div><p><strong>interface.html</strong></p><div class="codebox"><pre><code>
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text-html; charset=utf-8&quot;&gt;
&lt;meta http-equiv=&quot;MSThemeCompatible&quot; content=&quot;yes&quot;&gt;
&lt;style type=&quot;text/css&quot;&gt;
	/* Задание общих стилей оформления элементов. Все размеры задавать только в pt! (Иначе будут проблемы с нестандартным DPI) */
	* {font:8pt MS Shell Dlg;}
	td {white-space:nowrap; padding-left:8pt;}
	.test {color:red; background-color:yellow;}
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
	// Выбор элемента, показ всех его свойств, возврат его идентификатора
	function funcTest(i){
		var elements = document.getElementsByTagName(&#039;*&#039;);
		var i = Math.abs(Number(i)||0); if (i &gt;= elements.length) i = 0;
		var elem = elements[i];
		// Подсвечиваем элемент и показываем все его свойства
		elem.className = &#039;test&#039;;
		ShowElementProps(elem);
		elem.className = &#039;&#039;;
		i++;
		return Math.floor(i);
	}
	// Показ всех свойств заданного элемента
	function ShowElementProps(obj) {
		var props = [];
		for (var p in obj){
			try {
				var v = obj[p];
				if (v) props.push(p + &#039; = &#039; + String(v).substr(0,25));
			} catch (e) {}
		}
		alert(obj.tagName + &#039;\n---------------\n&#039; + props.sort().join(&#039;\n&#039;));
	}
&lt;/script&gt;
&lt;/head&gt;
&lt;body style=&quot;margin:10pt; overflow:hidden; background-color:#629DAC;&quot;&gt;
	&lt;fieldset&gt;&lt;legend&gt;Internet Explorer&lt;/legend&gt;
		&lt;table style=&quot;border-width:0; border-collapse:collapse; width:100%; height:28pt;&quot;&gt;
			&lt;tr&gt;
				&lt;td&gt;
					&lt;input id=&quot;IEButtonGet&quot; type=&quot;button&quot; value=&quot;Get from AHK&quot;&gt;
				&lt;/td&gt;
				&lt;td&gt;
					&lt;input id=&quot;IEInputBox&quot; style=&quot;width:160pt;&quot; value=&quot;test HTML string&quot;&gt;
				&lt;/td&gt;
				&lt;td&gt;
					&lt;input id=&quot;IEButtonSend&quot; type=&quot;button&quot; value=&quot;Send to AHK&quot;&gt;
				&lt;/td&gt;
			&lt;/tr&gt;
		&lt;/table&gt;
	&lt;/fieldset&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre></div><p>Сразу отвечу на вопрос: <strong>Почему HTML не вставлен в AHK скрипт, а находится в отдельном файле?</strong><br />Если в HTML всего пара или тройка элементов, то вставка кода в AHK скрипт вполне оправдана. Когда речь идет о более-менее серьезном проекте, то такая интеграция превращается в огромную проблему. Тут и неудобство редактирования инородного кода, и необходимость его преобразования, и отсутствие возможности тестирования,... (список можно продолжить). Это - проблемы, с которыми еще можно кое как справиться, но есть и неразрешимые.<br />При компиляции HTML можно оставить в отдельном файле (<span style="color: blue">FileInstall</span>), а можно добавить в ресурсы получившегося exe-файла (вручную, либо с помощью нового <a href="https://autohotkey.com/boards/viewtopic.php?f=24&amp;t=521">Ahk2Exe</a>). В общем, надеюсь, доказал. Внешний HTML - без вариантов.</p><p>Обсуждение данного шаблона ведётся в <a href="http://forum.script-coding.com/viewtopic.php?id=12589">этой</a> теме.</p>]]></content>
			<author>
				<name><![CDATA[mozers]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=4112</uri>
			</author>
			<updated>2017-04-07T09:45:36Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=114757#p114757</id>
		</entry>
</feed>
