简体   繁体   中英

Problem with the SetConsoleCursorPosition() function

I need a hand because I can't get the SetConsoleCursorPosition () function to work, I made a dll project and then I allocated the console with its main functions (cout and cin), but I don't know how to make that function work as well, in the sense that I do not go to the line that I have set, as the code ignored that instruction

void consolerefresh()
{
    static const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coord = { (SHORT)0, (SHORT)10 };
    SetConsoleCursorPosition(hConsole, coord);
    for (int i = 0; i < (sizeof(last) / sizeof(last[0])); i++)
    {
        if (last[i] != 2) {
            cout << last[i] << endl;
        }
            
    }
}

My allocConsole code:

void createconsole()
{
    AllocConsole();
    FILE* fDummy;
    freopen_s(&fDummy, "CONOUT$", "w", stdout);
    freopen_s(&fDummy, "CONOUT$", "w", stderr);
    freopen_s(&fDummy, "CONIN$", "r", stdin);
    std::cout.clear();
    std::clog.clear();
    std::cerr.clear();
    std::cin.clear();
   
}

EDIT: I fixed the error in the code but it still doesn't work.

Per SetConsoleCursorPosition , the first argument must be " a handle to the console screen buffer ". Per GetStdHandle , the handle to the active console screen buffer is returned by STD_OUTPUT_HANDLE , not STD_INPUT_HANDLE which is the handle to the console input buffer.

Using the correct handle will get SetConsoleCursorPosition to work as expected.

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  // instead of STD_INPUT_HANDLE

[ EDIT ] The following was verified to work in VS 2019 using a default wizard-generated Win app with the following code added around wWinMain .

//... wizard generated code

#include <stdio.h>
#include <iostream>

void consolerefresh()
{
    static const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coord = { 5, 5 };
    SetConsoleCursorPosition(hConsole, coord);
    std::cout << "at (5, 5)" << std::endl;
}

void createconsole()
{
    AllocConsole();
    FILE* fDummy;
    freopen_s(&fDummy, "CONOUT$", "w", stdout);
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    createconsole();
    consolerefresh();

    UNREFERENCED_PARAMETER(hPrevInstance);

//... rest of wizard generated code

Running the program creates a console window and displays the following.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM