我无法在格式化的MessageBox中打印一个数字

时间:2017-09-18 22:02:57

标签: winapi unicode printf messagebox

以下代码无法正常工作。 %i未与其变量相关联。

#include<Windows.h>
#include<stdio.h>
#include<tchar.h>

/*       SCREENSIZE.C

    This project contains the code that Programming Windows
    book by Charles Petzold is using.

*/


int cdecl MessageBoxPrintfW(TCHAR *msgBoxTitle, TCHAR *msgBoxFormat, ...)
{
    //define buffer
    TCHAR msgBoxBuffer[1024];

    //define iteration pointer
    va_list argPtr;

    //start iteration
    va_start(argPtr, msgBoxFormat);

    /*int _vsnwprintf_s(
    wchar_t *const _Buffer,
    const size_t _BufferCount,
    const size_t _MaxCount,
    const wchar_t *const _Format,
    va_list _ArgList)
    */

    _vsntprintf_s(msgBoxBuffer, sizeof(msgBoxBuffer) / sizeof(TCHAR), (sizeof(msgBoxBuffer) / sizeof(TCHAR)) - 1, msgBoxFormat, argPtr);

    //end iteration 
    va_end(argPtr);

    //Use return type to pass preconfigured MessageBox(0,"Text","Title",MB_OKCANCEL);
    //Whe we use L before a string example: L"text" it is considered UNICODE format.

    return(MessageBox(0, msgBoxFormat, msgBoxTitle, MB_OKCANCEL));
}

int WINAPI WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR pCmdLine,
    int iCmdShow)
{
    int cxScreen, cyScreen;
    cxScreen = GetSystemMetrics(SM_CXSCREEN);
    cyScreen = GetSystemMetrics(SM_CYSCREEN);

    MessageBoxPrintfW(TEXT ("SCREENSIZE"), TEXT("The screen is %i pixels wide by %i pixels high."), cxScreen, cyScreen);

    return(0);
}

为什么会这样?

以下是我得到的输出:

output

1 个答案:

答案 0 :(得分:2)

TCHAR msgBoxBuffer[1024];
_vsntprintf_s(msgBoxBuffer,...
...
return(MessageBox(0, msgBoxFormat, msgBoxTitle, MB_OKCANCEL));

请注意,您正在写信至msgBoxBuffer,但您从未使用msgBoxBuffer。所以你的消息框不会改变任何东西。请尝试以下方法:

int MessageBoxPrintfW(const TCHAR *msgBoxTitle, const TCHAR* msgBoxFormat, ...)
{
    va_list args;
    va_start(args, msgBoxFormat);

    int len = _vsctprintf(msgBoxFormat, args) + 1; // add terminating '\0'
    TCHAR *buf = new TCHAR[len];
    _vstprintf_s(buf, len, msgBoxFormat, args);

    int result = MessageBox(0, buf, msgBoxTitle, MB_OKCANCEL);

    delete[]buf;

    return result;
}

对于C版本,使用malloc(len * sizeof(TCHAR))代替new,并使用free代替delete[]