Older Version Newer Version

Alyce Alyce Jan 8, 2007

 =Getting a Window's Coordinates=

The GetWindowRect API call from user32.DLL retrieves the coordinates of a window. It requires a handle to the window, which is obtained with Liberty BASIC's HWND() function. It also requires a struct to receive the coordinates. The members of the struct indicate the X,Y positions of the upper left corner and lower right corner of the window. The struct looks like this:

[[code format="vbnet"]]
struct Rect, x1 As Long, y1 As Long, x2 As Long, y2 As Long
[[code]]

The x1 member gives the left X coordinate. The y1 member gives the top Y coordinate. The x2 member gives the right X coordinate and the y2 member gives the bottom Y coordinate. The upper left corner location is at (x1, y1) and the lower right corner is at (x2, y2). Notice that x2 and y2 are not the width and height of the window, but rather they are the location on the screen of the right and bottom sides of the window.

The function looks like this:

[[code format="vbnet"]]
handle = hwnd(#1)
CallDLL #user32, "GetWindowRect",handle as uLong,Rect As struct, result As Long
[[code]]

After the function returns, the coordinates are in the Rect struct and can be retrieved like this:

[[code format="vbnet"]]
ulx = Rect.x1.struct  'left x coord
uly = Rect.y1.struct  'upper y coord
lrx = Rect.x2.struct  'right x coord
lry = Rect.y2.struct  'lower y coord
width  = lrx - ulx    'right x minus left x
height = lry - uly    'lower y minus upper y
[[code]]

Here's a little demonstration program that gets the window coordinates.

[[code format="vbnet"]]
nomainwin
open "test" for window as #1
#1 "trapclose Quit"

struct Rect, x1 As Long, y1 As Long, x2 As Long, y2 As Long
handle = hwnd(#1)
CallDLL #user32, "GetWindowRect",handle as uLong,Rect As struct, result As Long

ulx = Rect.x1.struct  'left x coord
uly = Rect.y1.struct  'upper y coord
lrx = Rect.x2.struct  'right x coord
lry = Rect.y2.struct  'lower y coord
width  = lrx - ulx    'right x minus left x
height = lry - uly    'lower y minus upper y
notice "Window is at ";ulx;", ";uly;" and is ";width;" wide and ";height;" high."

wait

sub Quit hndle$
close #hndle$
end
end sub
[[code]]