win32 ruby 全局热键

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#!/usr/bin/env ruby
# -*- coding: gb18030 -*-
# __FILE__ : hotkey.rb
# 2012-7
# ruby 1.9
#gem 1.8
#gem install win32-api windows-pr windows-api cstruct 
#在Ruby中方便的调用Win32 API (使用windows-pr和CStruct) :
#http://www.w-yong.com/docs/ruby_win32_api.html

require 'rubygems' 

require 'windows/window'
include Windows::Window

#打开D:\ruby193\lib\ruby\gems\1.9.1\gems\windows-pr-1.2.2\lib\windows\window.rb, 
#加入这行 API.new('GetAsyncKeyState', 'L', 'I', 'user32')
module Windows
  module Window
    API.new('GetAsyncKeyState', 'L', 'I', 'user32')
  end
end

class Hotkey
	def ck(keycode)
		GetAsyncKeyState(keycode.ord)
	end
	def press?(keycode)
		GetAsyncKeyState(keycode.ord)
		GetAsyncKeyState(keycode.ord) != 0
	end

	#显示按下的键
	def guess
		255.times{|x|
			tmp = GetAsyncKeyState(x)
			if tmp != 0
				print "\n \"#{x.chr}\" pressed code=#{x} stat=#{tmp} " 
			end
		}
	end

	def loopcheck
		`title ctrl+c 退出`
		loop do
			sleep 0.02
			#print("\nctrl:", ck(17), "\t" )
			guess #具体win32 keycode的定义,搜索 Key Code Constants
			cc if press?(17) and press?('C')
		end
	end
	def cc
		exit
	end
end

if $0 == __FILE__
	Hotkey.new.loopcheck
end