Hi,
I am having a slight problem trying to centre my Win32 client to the screen. I am aware that it is a small piece of code, but I just can't get past that problem. If anyone could help that would be much appreciated.
Thanks
Printable View
Hi,
I am having a slight problem trying to centre my Win32 client to the screen. I am aware that it is a small piece of code, but I just can't get past that problem. If anyone could help that would be much appreciated.
Thanks
Code:BOOL CenterWindow (HWND hwndChild)
{
RECT rChild, rWorkArea;
int wChild, hChild;
int xNew, yNew;
BOOL bResult;
// Get the Height and Width of the child window
GetWindowRect (hwndChild, &rChild);
wChild = rChild.right - rChild.left;
hChild = rChild.bottom - rChild.top;
// Get the limits of the 'workarea'
bResult = SystemParametersInfo(
SPI_GETWORKAREA, // system parameter to query or set
sizeof(RECT),
&rWorkArea,
0);
if (!bResult) {
rWorkArea.left = rWorkArea.top = 0;
rWorkArea.right = GetSystemMetrics(SM_CXSCREEN);
rWorkArea.bottom = GetSystemMetrics(SM_CYSCREEN);
}
// Calculate new X position, then adjust for workarea
xNew = (rWorkArea.right /2) - wChild/2;
// Calculate new Y position, then adjust for workarea
yNew = (rWorkArea.bottom/2) - hChild/2;
// Set it, and return
return SetWindowPos (hwndChild, NULL, xNew, yNew, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
See rather the CenterWindow() finction from MSDN
Thanks for the code. Its much appreciated.
Which part of the code will I place it?
Technically that code centers a window in the desktop area, not on a screen. This means that in a two monitor setup it would end up cut in half at the adjoining edge of each screen, which can be pretty annoying.
GetWindowRect and SystemParameters info only give the dimensions of the primary display. If you wish to center the window on the secondary display or possibly split the window up between the primary and secondary display, you will have to write additional code to get the virtual screen dimensions. The OP in this thread had a problem with only being able to display a screensaver window on the primary display. Eventually he realized that he would have to use MonitorInfoEx to determine the virtual screen size in order to cover both displays with his screensaver window.
You can also use the undocumented DS_CENTER style on dialogs (in MSVC at least).