The AppleScript solution—for which see Anne's answer—is by far the easiest.
If you want to give this to friends who can't be relied on to figure out how to enable assistive access, or distribute it more widely, just add this line:
do shell script ¬
"touch /private/var/db/.AccessibilityAPIEnabled" ¬
with administrator privileges
This will pop up the usual auth dialog and then use the privileges to turn on assistive access.
It is actually possible to do this without assistive access, but it requires using private functions within CoreGraphics/Quartz Window Services, namely CGSPrivate.h.
With public APIs, you can easily enumerate all of the windows:
CFArrayRef windows =
CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly |
kCGWindowListExcludeDesktopElements,
kCGNullWindowID);
This returns an array of dictionaries, and each dictionary contains a kCGWindowBounds dictionary, which has Height, Width, X, and Y integer values.
But these public APIs are strictly read-only. To actually move the windows, you have to dip into CGSPrivate.h to do something like this:
CGSConnection conn = _CGSDefaultConnection();
for (NSDictionary *window in windows) {
CGSWindow wid = (CGSWindow)[[window objectForKey:@"kCGWindowNumber"] intValue];
CGRect bounds;
CGRectMakeWithDictionaryRepresentation([window objectForKey:@"kCGWindowBounds"],
&bounds);
CGSMoveWindow(conn, wid, bounds.origin);
}
Obviously, this is pretty nasty, and you should only consider it if you really need to distribute an app that can't ask for assistive access.
You could also reverse-engineer the Window Server protocol and talk to it directly, but this is even nastier.