Kevin Shin
Kevin Shin

Reputation: 13

How to display variables on windows api message box C programming

I'm trying to print out a variable to a message box from Language C This is my current code

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

my attempt was assigning the string which included a variable and then I putting that assigned string into the MessageBox but whenever I compiled this It will give me a warning saying

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

would there be any solution to this? I am currently using Visual Studio 2017

Upvotes: 0

Views: 1522

Answers (1)

cup
cup

Reputation: 8237

MessageBox is actually a macro - there are two versions: MessageBoxA which takes chars and MessageBoxW which takes wide chars. Depending on the default character set, it will take either the A or W version. By default, it takes the W version.

If you go into the project properties, under general, near the bottom of the dialog, there is an entry for character set. By default, it is set to unicode (the W version). Just change this to MBCS (Multi byte character set) and your program should build after you've removed the L from the MessageBox title

Alternatively leave it as Unicode and change the code to the following. Note that you don't need winmain if it is not using the GUI. You can use MessageBox in a console application

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

There is a third solution using TCHAR but I'll have to look it up before I post it.

Edit the third solution If you look in stdafx.h, it has probably already included tchar.h. These are character agnostic definitions. You can use a MessageBox with a C++ Win32 console application.

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

Upvotes: 2

Related Questions