keyhac で選択文字列を Google 検索
keyhac で「選択文字列を Google 検索」を実現するには次のようにする。
def configure(keymap): keymap_global = keymap.defineWindowKeymap() def launch_selstr(prefix = u"", suffix = u""): def _launch_selstr(): keymap.command_InputKey("C-C")() shellExecute(None, None, prefix + getClipboardText() + suffix, "", "", SW_NORMAL) return _launch_selstr keymap_global["W-2"] = launch_selstr(ur"http://www.google.com/search?q=")
この例では Win+[ 2 ] で選択文字列をコピーすると同時に Google 検索する。*1
keyhac v1.08 では keymap_global[] = の右辺に文字列と呼び出し可能オブジェクトを同時に指定することはできないので、このように「『shellExecute() を実行する関数』を返す関数」を自分で作り、その中で keymap.command_InputKey("C-C")() を実行する。keymap.command_InputKey("C-C") 自体は「キー入力を行う関数を返す関数」なので、後に () を付けてキー入力を行う関数を実行させなければならない。
本当はこれで済むはずなんだけど、クリップボードユーティリティが常駐してる環境だと Ctrl+[ C ] を送信してから実際にクリップボードが書き換わるまでに少しタイムラグがあるようだ。keyhac 側 (というか pyauto 側?) でウェイトができればいいんだけど、今のところそういう関数はないようなので、とりあえず対症療法的に次のようにしてみた。
def launch_selstr(prefix = u"", suffix = u""): def _launch_selstr(): prevclipboardtext = getClipboardText() count = 0 while getClipboardText() == prevclipboardtext and count < 20: keymap.command_InputKey("C-C")() count += 1 shellExecute(None, None, prefix + getClipboardText() + suffix, "", "", SW_NORMAL) return _launch_selstr keymap_global["W-2"] = launch_selstr(ur"http://www.google.com/search?q=")
ちなみに同じことを窓使いの憂鬱でやるとこんな感じ。別途 google.vbs (後述) が必要。
key W-I = C-C &Wait(100) &ShellExecute("open", "E:\\AppData\\mayu\\google.vbs", $Clipboard,, ShowNormal)
' google.vbs Dim wshshell, cmd Set wshshell = WScript.CreateObject("WScript.Shell") cmd = "rundll32.exe url.dll,FileProtocolHandler http://www.google.co.jp/search?q=" cmd = cmd & getarguments wshshell.Run cmd, 1, False Function getarguments() Dim a, s For Each a In WScript.Arguments s = s & Replace(a, vbcrlf, " ") & " " Next getarguments = s End Function
同じことを AutoHotkey でやるとこんな感じ。この例では ClipUty.ahk を使ってクリップボードの内容を保全している。
#Include ClipUty.ahk launch_selstr(prefix = "", suffix = "") { ClipUty(0x01) ; 退避 selstr := ClipUty(0x02, "", 1) ;コピー loop parse, selstr, `n { cmdline := prefix . A_LoopField . suffix run % cmdline break ; 最初の1行だけ } ClipUty(0x08) ; リストア } #2:: launch_selstr("http://www.google.com/search?q=", "")