Apply a single thin bead of minimally expanding polyurethane foam to the gap between the window and the framing. Allow the bead to expand and cure for one hour before adding more. Repeat until the cavity is completely filled. This type of foam won't push the window frame out of square as it expands, as some other foams will.
If the gap is too narrow for the nozzle of a spray foam can, seal the bead with a bead of caulk.
In case you're wondering, here's how a window is installed:
http://www.thisoldhouse.com/toh/how-to/intro/0,,218006,00.html?xid=yahoo-answers&partner=yes
exact fit windows
adjustable fit windows
Most windows are not exact fit windows and need to be shimmed so they can be leveled and adjusted properly. The gap can be filled in with an expanding foam to seal up any cracks or air leaks, helping to better insulate your house. Just make sure that the type you get states that it is for windows and doors. Other types can expand too much and bend or bow your door or window frame. Add a little bit of foam at a time. Any excess can be trimmed off even with a knife or small saw blade. If the crack is too small for the foam nozzle, use calking. Make sure to wear old clothes and to cover up the carpet on the floor with plastic. If you get the foam on your clothes or carpet it can be difficult to almost impossible to remove.