tags:

views:

94

answers:

3

Win32's FindWindow() can find a window having the title of "Untitled - Notepad", but what if I just want to find a Notepad window but don't know whether it is "try.bat - Notepad" or some other file name on the title bar?

It seems that if the title is passed in a NULL value, then any window will be returned, but only one window is returned, so there is no way to grep for the title using regular expression.

(I am doing this using Ruby's Win32API)

+1  A: 

You almost certainly want to use the EnumWindows function; this function will call you back with a window handle, and then you can use GetWindowText to inspect the window title and find the one you want.

Now, I have no idea how to write a callback function in Ruby, so you'll need some help there.

Eric Brown
yeah, I wonder too... that the Win32 callback function is expected to be a C function probably, so how can it call a Ruby function
動靜能量
+2  A: 

I would follow Eric's advice to use EnumWindows. You can provide Ruby callbacks to Windows API functions through win32-api. Here's an example that was trivially modified from the sample in the win32-api README:

require 'win32/api'
include Win32

# Callback example - Enumerate windows
EnumWindows     = API.new('EnumWindows', 'KP', 'L', 'user32')
GetWindowText   = API.new('GetWindowText', 'LPI', 'I', 'user32')
EnumWindowsProc = API::Callback.new('LP', 'I'){ |handle, param|
  buf = "\0" * 200
  GetWindowText.call(handle, buf, 200);

  if (!buf.index(param).nil?)
    puts "window was found: handle #{handle}"
    0 # stop looking after we find it
  else
    1
  end
}

EnumWindows.call(EnumWindowsProc, 'Firefox')
Steven
it works perfect! I have always been using `require 'Win32API'` and it seems that `win32/api` and `WIN32API` are different. Does any one know a place for documentation and examples? The main site seems to be http://rubyforge.org/frs/?group_id=85
動靜能量
+2  A: 

The 1st argument of FindWindow searches by class name, if you use "Notepad" (Notepad's main window class name) for this and a null title you would get the 1st matching handle irrespective of its caption.

Alex K.