centering a dialog box
I'm working on an assignment from school and i'm stuck... I'm working on VC++ 6.0 and I need to center a dialog box with a click of a button after it's been moved. Can anybody help me by giving me a starting point? I know it has something to do with math but i just don't know where to start.
I really appreciate it. ;)
use GetDesktopWindow() and GetWindowRect() to find the entire screen dimensions.
Then use the dilogs HWND and GetWindowRect() to find its dimensions.
The offset from the left and top is found with some simple math. Fill a rect with the offsets for upper left and add the dimensions of the dialog to get lower right.
Use SetWindowPos() ect to reposition the window.
I did this like an hour ago :) Very ironic!
Here's what I've got:
The math is pretty simple... If you want to center a window, you first need the coordinates of the center of the screen, so you get the screen width and divide by 2 and the screen height and divide by 2... then in order to get the window's upper-left coordinates for ::SetWindowPos(), you need to subract half of the window's width from the screen center position, and subtract half of the window's height from the screen center position. You get the window's width and height with ::GetWindowRect() and then by subtracting its right side position from its left side for width, and bottom side position from its top side position for its height.
::SetWindowPos(hDlg, HWND_TOPMOST, (::GetSystemMetrics(SM_CXSCREEN)/2 - ((Rect.right - Rect.left)/2)),
(::GetSystemMetrics(SM_CYSCREEN)/2 - ((Rect.bottom - Rect.top)/2)),
(Rect.right - Rect.left), (Rect.bottom - Rect.top), SWP_SHOWWINDOW);
I've also learned that ::GetWindowRect() will retrieve a window's RECT even if the window is hidden (I guess from last known coordinates)... just a random little info :)
Thanks for your help, we must be in the same class... hehe ;)
I did this for a small project of mine, and I found that I liked to center the dialog in the screen's workable area using the SystemParametersInfo function. Use the SPI_GETWORKAREA parameter to get this information. Of course, this is just a personal preference, but I thought I should suggest it as an alternative.