Win api MessageBox 备选方案,其中包含一组文本对齐:居中

Win api MessageBox alternative that has a set for text-align: center

正如我通过搜索发现的那样,无法创建文本居中的 MessageBox()

那么是否有一些简单的替代方法提供 MessageBox() 功能(包括程序等待 closing/accepting 框 ),可以选择居中对齐文本?

感谢 suggestions/examples。

PS:在 Windows7+ 上,使用 C++ Windows API(在 MS Visual Studio 2012 中编译)

编辑:
一些有用的提示:
1) Visual Studio 的 Express 版本没有资源 editor/file 创建选项:

2) Visual Studio C++ how to display a dynamic message (i.e., string) in my About box?

Afaik 没有。但使用 Win32 资源和 DialogBox function.

创建这样的对话框实际上很容易

As I found out by searching, it is not possible to create a MessageBox() with center-aligned text.

无法创建 居中对齐的 MessageBox() 对话框,因为 API 没有为此提供选项。但是 可以 操纵 标准 MessageBox()` 对话框,使用一些小技巧来强制它居中对齐。

使用SetWindowsHookEx() to create a WH_CBT hook for the thread that is calling MessageBox() (no DLL needed). The hook callback allows you to discover the HWND of the dialog that MessageBox() creates. With that, you can manipulate it however you want. In this case, you can use FindWindowEx() to get the HWND of the STATIC control for the dialog's text and then apply the SS_CENTER style to it using SetWindowLong()。例如:

LRESULT CALLBACK CenterMsgBoxTextProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HCBT_ACTIVATE)
    {
        HWND hDlg = (HWND) wParam;
        HWND hTxt = FindWindowEx(hDlg, NULL, TEXT("STATIC"), NULL);
        if (hTxt)
            SetWindowLong(hTxt, GWL_STYLE, GetWindowLong(hTxt, GWL_STYLE) | SS_CENTER);
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

HHOOK hHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) &CenterMsgBoxTextProc, NULL, GetCurrentThreadId());
MessageBox(...);
if (hHook) UnhookWindowsHookEx(hHook);

或者,您可以使用 SetWinEventHook() 而不是 SetWindowsHookEx()

void CALLBACK CenterMsgBoxTextProc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
    HWND hTxt = FindWindowEx(hwnd, NULL, TEXT("STATIC"), NULL);
    if (hTxt)
        SetWindowLong(hTxt, GWL_STYLE, GetWindowLong(hTxt, GWL_STYLE) | SS_CENTER);
}

HWINEVENTHOOK hHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_CREATE, NULL, &CenterMsgBoxTextProc, GetCurrentProcessId(), GetCurrentThreadId(), 0);
MessageBox(NULL, TEXT("test"), TEXT("test"), MB_OK);
if (hHook) UnhookWinEvent(hHook);

两种情况下的结果如下: