Last active
October 19, 2017 01:27
-
-
Save kurogelee/0a8f73c0201dfec59c32 to your computer and use it in GitHub Desktop.
Clojureでキーボード操作をエミュレートする ref: http://qiita.com/kurogelee/items/0be411023e5e95dadbad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns robot.sample | |
(:import [java.awt Robot] | |
[java.awt.event KeyEvent] | |
[javax.swing KeyStroke])) | |
(defn static-fields [^Class class fields] | |
(map #(load-string (str (.getName class) "/" %)) fields)) | |
(defn modifiers->vks [modifiers] | |
(->> (map #(when (pos? (bit-and modifiers %1)) %2) | |
(static-fields KeyEvent '[SHIFT_DOWN_MASK CTRL_DOWN_MASK ALT_DOWN_MASK ALT_GRAPH_DOWN_MASK META_DOWN_MASK]) | |
(static-fields KeyEvent '[VK_SHIFT VK_CONTROL VK_ALT VK_ALT_GRAPH VK_META])) | |
(filter identity))) | |
(defn stroke->vks [^String stroke] | |
(let [^KeyStroke ks (KeyStroke/getKeyStroke stroke) | |
vks (modifiers->vks (.getModifiers ks))] | |
(concat vks [(.getKeyCode ks)]))) | |
(def ^:dynamic *sleep-time* 100) | |
(defn emulate-stroke [^Robot robot ^String stroke] | |
(Thread/sleep *sleep-time*) | |
(let [vks (stroke->vks stroke)] | |
(doseq [vk vks] | |
(.keyPress robot vk)) | |
(doseq [vk (reverse vks)] | |
(.keyRelease robot vk)))) | |
(defn emulate-strokes [^Robot robot & strokes] | |
(doseq [stroke strokes] | |
(emulate-stroke robot stroke))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def bot (Robot.)) | |
(emulate-strokes bot "P" "shift T" "B" "shift A" "TAB") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment