LoginSignup
11
11

More than 5 years have passed since last update.

Windowsでアクティブになっているアプリケーションの名前をRubyでFiddleを使って取得

Posted at

昨日、Rubyを使ってWin32APIを叩きWindowsでアクティブになっているアプリケーションの名前を取得しましたが 、Ruby2.0以降からはFiddleを使ってWindows系の関数を叩くのが標準となったようです。

そこで昨日と同じコードをRuby2.0以降の標準で記載するには、どのように書けばよいのかっということで記載してみました。

動作環境は昨日と同じく、Ruby2.0とRuby2.1で動作確認済み。Ruby2.2は未確認
Windows環境はWindows7を使用、Windows8環境下で動くかは未確認です。

main.rb
require "fiddle/import"
require 'fiddle/types'

module WIN32API
  extend Fiddle::Importer
  dlload 'C:\\Windows\\System32\\user32.dll'
  include Fiddle::Win32Types

  extern 'HWND GetForegroundWindow()'
  extern 'int GetWindowText(HWND, char*, int)'
  extern 'int GetWindowTextLength(HWND)'
end

loop{
  hwnd = WIN32API.GetForegroundWindow
  buf_len = WIN32API.GetWindowTextLength(hwnd)
  str = ' ' * (buf_len + 1)
  result = WIN32API.GetWindowText(hwnd, str, str.length)

  p str.encode(Encoding.default_external)

  sleep 1
}

ソースコードとしては長くなりましたが、C言語やC++で呼び出すように呼び出せるようになったので、直感的にはわかりやすくなったかなっと思います。
また extern で記載する際も、実際の関数呼び出しの呼び方を定義しているため、わかりやすいかと思います。

11
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11