require 'ffi' module Win VK_VOLUME_DOWN = 0xAE; VK_VOLUME_UP = 0xAF; VK_VOLUME_MUTE = 0xAD; KEYEVENTF_KEYUP = 2 extend FFI::Library ffi_lib 'user32' ffi_convention :stdcall attach_function :keybd_event, [ :uchar, :uchar, :int, :pointer ], :void # simulate pressing the mute key on the keyboard keybd_event(VK_VOLUME_MUTE, 0, 0, nil); keybd_event(VK_VOLUME_MUTE, 0, KEYEVENTF_KEYUP, nil); end
This example shows the common task of calling a native function with a pointer to a new struct, then using that same struct once it has been populated and returned by the native function.
This example shows how to use a native function that takes a callback specifying simple input parameters. The callback itself calls a native function which returns a string via its pointer to a character buffer parameter.
Note that the param you can pass “through” to the enum call is basically a pointer. An example of using this pointer for multiple objects can be found in the win32screenshot gem.
This example shows how to use Unicode text from Ruby with the Unicode version of the
MessageBox Windows API function.
There are three crucial points shown in the Ruby FFI code:
MessageBoxW) is explicitly specified to FFI’s
:stringparameter types (as would normally be used with the
:buffer_inparameter types are used for Unicode strings. In Ruby-FFI
:stringmeans “null terminated C string” where UTF-16 is closer to a binary blob of data that can contain NULL bytes. NOTE: currently Ruby-FFI checks for NULL chars in
:stringparameters to help avoid NULL byte poisoning attacks from outside string sources.
This example shows how to interface with a native function that takes a pointer to a struct which contains an embedded union, both of which are populated before being provided to the native function.
The above FFI code takes a shortcut in the name of saving wiki page space. The actual Windows
INPUT struct contains an anonymous union member with
HARDWAREINPUT members. As the
MOUSEINPUT struct is the largest of these members, we can get away with the hacky
InputEvent FFI union definition for example purposes.
TODO explain FFI syntax for embedded struct members which is opposite of typical C usage.
Bringing windows to the foreground is tricky, since no single call seems to always force it to the foreground.
http://betterlogic.com/roger/?p=2950 describes how.
Note that for windows’ core working you use a @ ffi_convention :stdcall@ but with normal DLL’s it appears you do not see here
FindWindowfunction gets defined as either
another good list (the VB list at the bottom is especially helpful)
A few gems use FFI with the windows API.