How can I center a Dialog Box over main program window position?

c, win32gui, winapi, window

Solution

From:

http://msdn.microsoft.com/en-gb/library/windows/desktop/ms644996(v=vs.85).aspx

case WM_INITDIALOG: 

// Get the owner window and dialog box rectangles. 

if ((hwndOwner = GetParent(hwndDlg)) == NULL) 
{
    hwndOwner = GetDesktopWindow(); 
}

GetWindowRect(hwndOwner, &rcOwner); 
GetWindowRect(hwndDlg, &rcDlg); 
CopyRect(&rc, &rcOwner); 

// Offset the owner and dialog box rectangles so that right and bottom 
// values represent the width and height, and then offset the owner again 
// to discard space taken up by the dialog box. 

OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); 
OffsetRect(&rc, -rc.left, -rc.top); 
OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); 

// The new position is the sum of half the remaining space and the owner's 
// original position. 

SetWindowPos(hwndDlg, 
             HWND_TOP, 
             rcOwner.left + (rc.right / 2), 
             rcOwner.top + (rc.bottom / 2), 
             0, 0,          // Ignores size arguments. 
             SWP_NOSIZE); 

if (GetDlgCtrlID((HWND) wParam) != ID_ITEMNAME) 
{ 
    SetFocus(GetDlgItem(hwndDlg, ID_ITEMNAME)); 
    return FALSE; 
} 
return TRUE; 

Problem

I've got this code to open an InputBox defined on a DLL that get HMODULE that I save on hInstance variable when main program calls. How can I center it over the main program window? It occurs that doesn't work and shows the DialogBox on top left on Screen or on top left of program window randomly. ``` #include <windows.h> #include "resource.h" char IB_res[10]; double defaultValue = 0; BOOL CALLBACK InputBox_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: if (defaultValue != -1) SetDlgItemText(hwnd, IDC_EDIT, (LPCSTR)(my_printf("%f", defaultValue).c_str())); else SetDlgItemText(hwnd, IDC_EDIT, (LPCSTR)""); return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: if (!GetDlgItemText(hwnd, IDC_EDIT, IB_res, 10)) *IB_res = 0; case IDCANCEL: EndDialog(hwnd, wParam); break; } break; default: return FALSE; } return TRUE; } DWORD processId; HWND hwndParent; BOOL CALLBACK enumWindowsProc(HWND hwnd, LPARAM lParam) { DWORD procid; GetWindowThreadProcessId(hwnd, &procid); if (procid == processId) hwndParent = hwnd; return TRUE; } HINSTANCE hInstance; const char* InputBox(double def_value) { defaultBetValue = def_value; processId = GetCurrentProcessId(); EnumWindows(enumWindowsProc, 0); INT_PTR ret = DialogBox(hInstance, MAKEINTRESOURCE(IDD_IB), hwndParent, InputBox_WndProc); DWORD error = GetLastError(); if (ret != IDOK) *IB_res = 0; return IB_res; } ```

Original source