Prompting user input in a windowed application, without window

Recently I had to to prompt my user for a number before starting my windowed application and looked for a function to generate sort of a MessageBox but with an input field.

Doesn’t exist apparently.

So I did something that allocates a console to the program, prompt the user classic style with a cin >> variable (would also probably work with other methods, such as scanf and other).

Here’s the code:

#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
AllocConsole();
freopen(“CONIN$”, “r”, stdin);
freopen(“CONOUT$”, “w”, stdout);
freopen(“CONOUT$”, “w”, stderr);

string message = “”;
cout << “Enter a message:” << endl;
cin >> message;

FreeConsole();

// string -> wstring
std::wstring wmessage;
wmessage.assign(message.begin(), message.end());

MessageBox(NULL, (LPCWSTR)&wmessage, L”Your input”, MB_OK);

return EXIT_SUCCESS;
}

Leave a Reply

Your email address will not be published. Required fields are marked *