-3

I am creating a console application and I need to center the text. This is my code:

void centerText(const char* word)
{
    HWND hwnd = GetConsoleWindow();
    RECT rct;
    GetWindowRect(hwnd, &rct);
    HDC dc = GetDC(hwnd);
    _bstr_t msg(word);
    DrawText(dc, msg, -1, &rct, DT_CENTER | DT_SINGLELINE);
    ReleaseDC(hwnd, dc);
}

But the "word/msg" doesn't show. Thank you for your help.

DMunoz
  • 1
  • 5
    `DrawText` is for GUI windows. – drescherjm Feb 08 '19 at 17:36
  • 4
    For a pure text-only application, there are ways to find out the dimensions of the console window *in characters*. From that it's relatively simple to find the center "point" and position the text around that. I suggest you read [this console function reference](https://learn.microsoft.com/en-us/windows/console/console-functions). – Some programmer dude Feb 08 '19 at 17:38
  • Related https://stackoverflow.com/questions/1937163/drawing-in-a-win32-console-on-c – drescherjm Feb 08 '19 at 17:38
  • For console applications simply use the standard library `std::cout`, `std::cin`. There's no need to resort to the winapi. Another good option is to use a portable _text based GUI_ library like e.g. ncurses, to cover the screen layout in a terminal window. – πάντα ῥεῖ Feb 08 '19 at 17:40
  • @πάνταῥεῖ And how exactly do you center text using only `std::cout`? You need the WinAPI to determine the width in characters of the console window. – zett42 Feb 08 '19 at 20:01
  • Possible duplicate of [c++ console screen size](https://stackoverflow.com/questions/26270019/c-console-screen-size) – zett42 Feb 08 '19 at 20:18
  • Another dupe: https://stackoverflow.com/q/8627327/7571258 – zett42 Feb 08 '19 at 20:19

1 Answers1

0

Does this work?

#include <windows.h>

bool centerText(const char* word)
{
    HANDLE hFile = CreateFileW(L"CONOUT$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);

    if (hFile)
    {
        short len = static_cast<short>(strlen(word));

        CONSOLE_SCREEN_BUFFER_INFO  csbi;
        GetConsoleScreenBufferInfo(hFile, &csbi);
        csbi.dwCursorPosition.X = (csbi.srWindow.Left - len)/2;
        SetConsoleCursorPosition(hFile, csbi.dwCursorPosition);

        puts(word);

        CloseHandle(hFile);
        return true;
    }

    return false;
}
spongyryno
  • 446
  • 2
  • 12