如何在Windows api消息框C上显示变量

时间:2020-06-20 06:37:48

标签: c visual-studio messagebox

我正在尝试从语言C将变量输出到消息框 这是我当前的代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreveInstance, LPSTR lpCmdLine, int nCmdShow)
{
    srand((unsigned int)time(NULL));
    int dice = (rand() % 20) + 1;
    char temp[128];
    sprintf(temp, "The die shows: %d", dice);

    MessageBox(NULL, temp, L"Dice", MB_YESNO);

    return 0;
}

我试图分配包含变量的字符串,然后将分配的字符串放入MessageBox中,但是每当我编译此字符串时,都会给我一个警告

error C2220: warning treated as error - no 'object' file generated
warning C4133: 'function': incompatible types - from 'char [128]' to 'LPCWSTR'
warning C4100: 'nCmdShow': unreferenced formal parameter
warning C4100: 'lpCmdLine': unreferenced formal parameter
warning C4100: 'hPreveInstance': unreferenced formal parameter
warning C4100: 'hInstance': unreferenced formal parameter

对此有什么解决办法吗? 我目前正在使用Visual Studio 2017

1 个答案:

答案 0 :(得分:2)

MessageBox实际上是一个宏-有两个版本:带字符的MessageBoxA和带宽字符的MessageBoxW。根据默认字符集,它将采用A或W版本。默认情况下,它使用的是W版本。

如果进入项目属性,通常在对话框底部附近,将出现一个字符集条目。默认情况下,它设置为unicode(W版本)。只需将其更改为MBCS(多字节字符集),然后从MessageBox标题中删除L即可构建程序。

或者将其保留为Unicode并将代码更改为以下内容。注意,如果不使用GUI,则不需要winmain。您可以在控制台应用程序中使用MessageBox

int main()
{
    srand((unsigned int)time(NULL));
    int dice = (rand() % 20) + 1;
    wchar temp[128];
    wsprintf(temp, L"The die shows: %d", dice);

    MessageBox(NULL, temp, L"Dice", MB_YESNO);

    return 0;
}

还有使用TCHAR的第三种解决方案,但是在发布之前,我必须先进行查找。

编辑第三个解决方案 如果您在stdafx.h中查找,它可能已经包含了tchar.h。这些是与字符无关的定义。您可以将MessageBox与C ++ Win32控制台应用程序一起使用。

#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include <Windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
    srand((unsigned int)time(NULL));
    int dice = (rand() % 20) + 1;
    TCHAR temp[128];
    _stprintf(temp, _T("The die shows: %d"), dice);

    MessageBox(NULL, temp, _T("Dice"), MB_YESNO);

    return 0;
}
相关问题