【问题标题】:How can I center a Dialog Box over main program window position?如何将对话框置于主程序窗口位置的中心?
【发布时间】:2012-11-27 20:48:54
【问题描述】:

我有这段代码可以打开一个在 DLL 上定义的 InputBox,该 DLL 获得 HMODULE,我在主程序调用时保存在 hInstance 变量中。我怎样才能把它放在主程序窗口的中心? 出现这种情况不起作用,并在屏幕左上角或程序窗口左上角随机显示对话框。

#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;
}

【问题讨论】:

    标签: c winapi window win32gui


    【解决方案1】:

    发件人:

    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; 
    

    【讨论】:

      最近更新 更多