3

我有这段代码可以打开一个在 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;
}
4

1 回答 1

7

从:

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; 
于 2014-09-19T11:09:11.443 回答