In Ruby there are 3 classes dedicated to windows users. The WIN32OLE class which is a client interface to windows 32 ole automation server, the WIN32OLE_EVENT class which is used in conjunction with the WIN32OLE class to add callbacks for Windows 32 events and the Win32API class that allows access to any arbitrary Windows 32 function.

I'll take only the Win32API class here. May be in other posts I'll cover the 2 others.

The Win32API has 3 methods: "new", "call" and "Call". The "new" method returns an object representing a windows API function. The "call" calls this API function with the given arguments and the "Call" method is a synonym for Win32API#call.

Let’s take an example of use. Lets change the desktop wallpaper: To change the desktop wallpaper we use the SystemParametersInfo function from user32.dll which takes 4 parameters: the action to perform (in our case the constant SPI_SETDESKWALLPAPER which is equal to 20), a constant that depends on the action (it must be 0 according to MS SDK), the bmp file to set as wallpaper and the last parameter is about whether we want to notify other open windows about the change, I set it to zero (no notification).


require 'Win32API'

desktop = Win32API.new("user32", "SystemParametersInfo", ['L','L','P','L'] , 'L')
desktop.Call(20,0,"c:/my_img.bmp",0)


The parameters to the "new" method are: the name of the dll that contains the function, the function name, an array of the function's parameters types and the last one is the type of the return value of the function. The parameters types allowed are: "n" and "l" represent numbers, "i" represents integers, "p" represents pointers to data stored in a string, and "v" represents a void type (used for the return value only).

To call the function SystemParametersInfo, we use the "Call" method of the object returned by "new" and give it all needed parameters.

Get it a try!

So, Ruby is not only for the web. You can use Ruby in a windows environment and create powerful applications in an object-oriented way.