<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AHK: Неадекватное поведение AHK (или меня)]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=10828&amp;type=atom" />
	<updated>2015-09-01T15:19:37Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=10828</id>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=97000#p97000" />
			<content type="html"><![CDATA[<p>Дополню тему, может кому понадобится пример использования таймеров в классе. Для того, чтобы скрипт из 1го сообщения работал, как предполагал <strong>Narrator</strong>, следует изменить методы <em>start</em> и <em>stop</em> таким образом:</p><div class="codebox"><pre><code>
    start() {
        timer := this.grab.bind(this)
        this.timer := timer
        setTimer, %timer%, 150
        ;return
    }

    stop() {
        timer := this.timer
        this.timer := &quot;&quot;
        setTimer, %timer%, delete
        ;return
    }
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Stremin]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33282</uri>
			</author>
			<updated>2015-09-01T15:19:37Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=97000#p97000</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96056#p96056" />
			<content type="html"><![CDATA[<p>Распишу<br /></p><div class="codebox"><pre><code>        setTimer, % this.grab(), 150</code></pre></div><p>подробнее:<br /></p><div class="codebox"><pre><code>       LabelOrFunctionName := this.grab()
       setTimer, % LabelOrFunctionName, 150</code></pre></div>]]></content>
			<author>
				<name><![CDATA[shiz]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26249</uri>
			</author>
			<updated>2015-07-26T13:21:59Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96056#p96056</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96055#p96055" />
			<content type="html"><![CDATA[<p><strong>shiz</strong>, Как это не в чем? Таймер то создает, функция работает, только каждая итерация таймера тянет за собой всех предков вплоть до кнопки. В процедурном программировании такого нет, следовательно, это неестественно и должно работать иначе. Получается, косяк AHK, поправьте если не прав.</p>]]></content>
			<author>
				<name><![CDATA[Narrator]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33230</uri>
			</author>
			<updated>2015-07-26T12:55:00Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96055#p96055</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96054#p96054" />
			<content type="html"><![CDATA[<p>В такой ситуации<br /></p><div class="codebox"><pre><code>        setTimer, % this.grab(), 150</code></pre></div><p>AHK не в чем винить — он делает точно то, что ему приказано: вызывает метод grab и создаёт таймер с меткой или функцией, имя которой (т.е. строку) возвращает grab (если бы возвращал).</p><p>Пробовал сделать<br /></p><div class="codebox"><pre><code>        setTimer, % ObjBindMethod(this, &quot;grab&quot;), 150</code></pre></div><p>но не получилось. Вот тут, возможно AHK и не справляется, но более вероятно, что я не всё понимаю.</p>]]></content>
			<author>
				<name><![CDATA[shiz]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26249</uri>
			</author>
			<updated>2015-07-26T12:23:11Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96054#p96054</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96053#p96053" />
			<content type="html"><![CDATA[<p>К сожалению, да, AHK в такой ситуации ведет себя неадекватно и пришлось запилить небольшой костыль. Если есть желание — можно развить тему, предложить свои варианты, я могу показать то, как я это обошел, если нет — тему можно закрывать. Благодарю <strong>Alectric</strong> за внимание и ставлю плюс ему в репу.</p>]]></content>
			<author>
				<name><![CDATA[Narrator]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33230</uri>
			</author>
			<updated>2015-07-26T11:50:44Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96053#p96053</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96048#p96048" />
			<content type="html"><![CDATA[<p><a href="http://forum.script-coding.com/viewtopic.php?pid=96044#p96044">Дополнил рассуждения.</a></p>]]></content>
			<author>
				<name><![CDATA[Alectric]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26027</uri>
			</author>
			<updated>2015-07-26T07:26:48Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96048#p96048</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96046#p96046" />
			<content type="html"><![CDATA[<p>Так работает, но подозреваю что не это требовалось:<br /></p><div class="codebox"><pre><code>; /// Точка входа

handler_1 := new Handler(&quot;vk5A&quot;,150)
handler_2 := new Handler(&quot;vk51&quot;,10)

F2::
if s:=!s
  settimer,send1,150
else
  settimer,send1,off
return

F3::
if s2:=!s2
  settimer,send2,10
else
  settimer,send2,off
return

send1:
handler_1.handle(&quot;Grabber&quot;)
return

send2:
handler_2.handle(&quot;Grabber&quot;)
return


class Handler {
    __new(key,deley) {
        this.vkKey := key
        this.Deley := deley
    }

    handle(module) {
        if (module == &quot;Grabber&quot;) {
            Send % &quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot;
        }
    }
}
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Alectric]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26027</uri>
			</author>
			<updated>2015-07-26T07:02:35Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96046#p96046</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96045#p96045" />
			<content type="html"><![CDATA[<div class="quotebox"><blockquote><div class="codebox"><pre><code>        setTimer, % this.grab(), 150</code></pre></div></blockquote></div><p>Ничего не запускал, но:<br />1) для начала, меня смущают круглые скобки: по таймеру должен вызываться метод grab или этот метод должен быть вызван однократно при создании таймера?!<br />2) если по таймеру должен вызываться метод grab, то не уверен, что в момент срабатывания таймера this будет разрешаться в объект, в методе start которого создан таймер.</p><p>По крайней мере в документации:<br /></p><div class="quotebox"><blockquote><div class="codebox"><pre><code>SetTimer [, Label, Period|On|Off|Delete, Priority]Parameters</code></pre></div><p>Label<br />&lt;...&gt;<br />[v1.1.20+]: If not a valid label name, this parameter can be the name of a function, or a single variable reference containing a function object. For example, SetTimer %funcobj%, 1000 or SetTimer % funcobj, 1000. Other expressions which return objects are currently unsupported.</p></blockquote></div>]]></content>
			<author>
				<name><![CDATA[shiz]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26249</uri>
			</author>
			<updated>2015-07-26T06:53:49Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96045#p96045</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96044#p96044" />
			<content type="html"><![CDATA[<p>Думаю что это проблема Autohotkey, ошибка или еще что-то. В общем, таймеры внутри классов не работают, да в принципе и не логично их так использовать, это же классы (в моем понимании - объекты с набором функций и индивидуальными параметрами одних и тех же переменных)... Может я и ошибаюсь, не изучал классы подробно.<br /></p><div class="codebox"><pre><code>; /// Точка входа

handler_1 := new Handler(&quot;vk5A&quot;,150)
handler_2 := new Handler(&quot;vk51&quot;,10)

F2::
if s:=!s
  handler_1.handle(&quot;Grabber&quot;)
else
  handler_1.stop_start(&quot;Grabber&quot;)
tooltip,% s,,0,3  ;  эта тултипка появляется несколько раз подрят от одного нажатия, как-будто скрипт перезапускается или... не знаю.
return

F3::handler_2.handle(&quot;Grabber&quot;)

return

class Grabber {
    __new(key,deley){
        this.vkKey := key
        this.Deley := deley
    }

    grab() {
        Send % &quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot;
        ;return
    }

    start() {
        setTimer, % this.grab(), % this.Deley ; если убрать этот таймер то все в порядке
        ;return
    }

    stop() {
        setTimer, % this.grab(), off
        ;return
    }
}

class Handler {
    __new(key,deley) {
        this.grabber := new Grabber(key,deley)
        this.grabberActive := false
        this.dotActive := false
    }

    handle(module) {
tooltip,% module &quot;`n&quot; this.grabberActive
        if (module == &quot;Grabber&quot;) {
            if (this.grabberActive == false) {
                this.grabber.start()
            } else {
                this.grabber.stop()
            }
        }
    }
    stop_start(module)
    {
tooltip,% module &quot;`n&quot; this.grabberActive,0,,2
        if (module == &quot;Grabber&quot;)
        {
          this.grabberActive := !this.grabberActive
        }
    }
}

</code></pre></div><p>Вот что дает одно нажатие F2:<br /></p><div class="codebox"><pre><code>007: if s:=!s  
008: handler_1.handle(&quot;Grabber&quot;)  
048: ToolTip,module &quot;&quot; this.grabberActive (0.03)
049: if (module == &quot;Grabber&quot;)  
050: if (this.grabberActive == false)  
051: this.grabber.start()  
030: SetTimer,this.grab(),this.Deley
025: Send,&quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot; (0.11)
027: }
032: }
052: }
055: }
056: }
011: ToolTip,s,,0,3
012: Return (0.16)
007: if s:=!s  
010: handler_1.stop_start(&quot;Grabber&quot;)  
059: ToolTip,module &quot;&quot; this.grabberActive,0,,2
060: if (module == &quot;Grabber&quot;)  
062: this.grabberActive := !this.grabberActive  
063: }
064: }
011: ToolTip,s,,0,3 (0.03)
012: Return (0.13)
007: if s:=!s  
008: handler_1.handle(&quot;Grabber&quot;)  
048: ToolTip,module &quot;&quot; this.grabberActive
049: if (module == &quot;Grabber&quot;)  
050: if (this.grabberActive == false)  
053: this.grabber.stop()  
035: SetTimer,this.grab(),off
025: Send,&quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot; (0.03)
027: }
037: }
054: }
055: }
056: }
011: ToolTip,s,,0,3
012: Return (0.95)</code></pre></div><p>Т.е. таймером является метка самой клавиши F2.</p><p>Даже если взять самый первый пример:<br /></p><div class="codebox"><pre><code>class Grabber {
    __new(){
        this.vkKey := &quot;vk5A&quot;
    }

    grab() {
        Send % &quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot;
        ;return
    }

    start() {
        setTimer, % this.grab(), 150
        ;return
    }

    stop() {
        setTimer, % this.grab(), off
        ;return
    }
}

class Handler {
    __new() {
        this.grabber := new Grabber
        this.grabberActive := false
    }

    handle(module) {

        if (module == &quot;Grabber&quot;) {
            if (this.grabberActive == true) {
                this.grabber.start()
                this.grabberActive := false
            } else {
;                this.grabber.stop()
                this.grabberActive := true
            }
        }
    }
}

; /// Точка входа

handler := new Handler

F2::
tooltip,% a_tickcount
handler.handle(&quot;Grabber&quot;)
return
</code></pre></div><p>Первое нажатие ничего не дает кроме тултипки, следующее запускает таймер вида:<br /></p><div class="codebox"><pre><code>settimer,f2,150

F2::
tooltip,% a_tickcount
return
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Alectric]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26027</uri>
			</author>
			<updated>2015-07-26T06:38:03Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96044#p96044</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96043#p96043" />
			<content type="html"><![CDATA[<p><strong>Alectric</strong>, да проблема не с таймером, проблема в том, что каждая его итерация дергает метод из совершенно другого класса, из-за чего все и слетает, ну я об этом в шапке написал)</p>]]></content>
			<author>
				<name><![CDATA[Narrator]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33230</uri>
			</author>
			<updated>2015-07-26T05:25:15Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96043#p96043</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96042#p96042" />
			<content type="html"><![CDATA[<p>Проблема с таймером, смотри код выше:<br /></p><div class="codebox"><pre><code>        setTimer, % this.grab(), % this.Deley ; если убрать этот таймер то все в порядке
 </code></pre></div>]]></content>
			<author>
				<name><![CDATA[Alectric]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26027</uri>
			</author>
			<updated>2015-07-26T05:21:18Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96042#p96042</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96041#p96041" />
			<content type="html"><![CDATA[<p><strong>Alectric</strong>, Спасибо, поправил название. В том то и дело, что нужно, чтобы работало так или очень близко к этому, на процедурном то и у меня работало, я об этом говорил в шапке, так что пример неуместен <img src="//forum.script-coding.com/img/smilies/sad.png" width="15" height="15" /></p>]]></content>
			<author>
				<name><![CDATA[Narrator]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33230</uri>
			</author>
			<updated>2015-07-26T05:19:06Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96041#p96041</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96040#p96040" />
			<content type="html"><![CDATA[<p>Что-то тут перемудрено так все... или я чего-то не понимаю?<br /></p><div class="codebox"><pre><code>vkKey=vk5a

f2::
state:=!state
settimer,loop,% state ? 0 : &quot;off&quot;
return

loop:
Send % &quot;{&quot; vkKey &quot; down}{&quot; vkKey &quot; up}&quot;
return
</code></pre></div><p>...</p><p>Тут хендлер два раза подряд выполняется, не знаю почему:<br /></p><div class="codebox"><pre><code>
class Grabber {
    __new(key,deley){
        this.vkKey := key
        this.Deley := deley
    }

    grab() {
        Send % &quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot;
        ;return
    }

    start() {
        setTimer, % this.grab(), % this.Deley ; если убрать этот таймер то все в порядке
        ;return
    }

    stop() {
        setTimer, % this.grab(), off
        ;return
    }
}

class Handler {
    __new(key,deley) {
        this.grabber := new Grabber(key,deley)
        this.grabberActive := false
        this.dotActive := false
    }

    handle(module) {
tooltip,% module &quot;`n&quot; this.grabberActive
        if (module == &quot;Grabber&quot;) {
            if (this.grabberActive == true) {
                this.grabber.start()
                this.grabberActive := false
            } else {
                this.grabber.stop()
                this.grabberActive := true
            }
        }
    }
}

; /// Точка входа

handler_1 := new Handler(&quot;vk5A&quot;,150)
handler_2 := new Handler(&quot;vk51&quot;,10)

F2::handler_1.handle(&quot;Grabber&quot;)
F3::handler_2.handle(&quot;Grabber&quot;)
</code></pre></div>]]></content>
			<author>
				<name><![CDATA[Alectric]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=26027</uri>
			</author>
			<updated>2015-07-26T04:29:19Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96040#p96040</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[AHK: Неадекватное поведение AHK (или меня)]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=96036#p96036" />
			<content type="html"><![CDATA[<p>Привет, ребят. Переписываю свой AHK-скрипт на ООП, вот этот крайне важный кусок кода работает некорректно. Я пробовал во всех вариациях, до которых смог додуматься, я убил 4 часа и гуглил как мог, выручайте!</p><div class="codebox"><pre><code>
class Grabber {
    __new(){
        this.vkKey := &quot;vk5A&quot;
    }

    grab() {
        Send % &quot;{&quot; this.vkKey &quot; down}{&quot; this.vkKey &quot; up}&quot;
        ;return
    }

    start() {
        setTimer, % this.grab(), 150
        ;return
    }

    stop() {
        setTimer, % this.grab(), off
        ;return
    }
}

class Handler {
    __new() {
        this.grabber := new Grabber
        this.grabberActive := false
    }

    handle(module) {

        if (module == &quot;Grabber&quot;) {
            if (this.grabberActive == true) {
                this.grabber.start()
                this.grabberActive := false
            } else {
                this.grabber.stop()
                this.grabberActive := true
            }
        }
    }
}

; /// Точка входа

handler := new Handler

F2::handler.handle(&quot;Grabber&quot;)

</code></pre></div><p>Написанный выше код нормально работает в процедурном стиле. Если из кода непонятно, то я хочу, чтобы по нажатию F2 начиналась бесконечная отправка клавиши z (vk5A), а если нажать еще раз — прекращалась.</p><p>Насколько я понял, каждая итерация цикла в setTimer дергает (ЗАЧЕМ?!) метод handle из совсем другого класса, из-за этого там меняются значение true/false и все работает криво, но может быть, я неправильно понял. Как с этим бороться? Как добиться нужного? Подскажите, пожалуйста, буду очень благодарен!</p><p>P.S. Пример рабочий, можно вставить и запустить.</p>]]></content>
			<author>
				<name><![CDATA[Narrator]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=33230</uri>
			</author>
			<updated>2015-07-25T21:30:55Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=96036#p96036</id>
		</entry>
</feed>
