提问者:小点点

我在C++中使用Windows.h头文件,并试图在VS中的控制台上画一条线,但我得到的是画出的线只是闪烁和?


我正在使用VS12,也在VS19上试过,但面临同样的问题,控制台窗口闪烁,并显示“按任意键继续”。 我对C++中的图形很陌生,所以如果有人能指导我更多关于C++中使用Windows.h头的图形,我会很高兴?

#include <iostream>
    #include <windows.h>
    #include <conio.h>
    #include <stdio.h>
    
    using namespace std;

void drawLine(int x1, int y1, int x2, int y2, int R, int G, int B) //use three 3 integers if you want colored lines.
{
    HWND consoleHandle = GetConsoleWindow();
    HDC deviceContext = GetDC(consoleHandle);

    //change the colour by changing the values in RGB (from 0-255) to get shades of gray. For other colors use 3 integers for color.
    HPEN pen = CreatePen(PS_SOLID, 2, RGB(R, G, B)); //2 is the width of the pen
    SelectObject(deviceContext, pen);
    MoveToEx(deviceContext, x1, y1, NULL);
    LineTo(deviceContext, x2, y2);
    DeleteObject(pen);
    ReleaseDC(consoleHandle, deviceContext);
}

void cls()
{
    COORD coordScreen = { 0, 0 };    // home for the cursor
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    if (!GetConsoleScreenBufferInfo(consoleHandle, &csbi))
    {
        return;
    }
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(consoleHandle, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten);
}

void showConsoleCursor(bool flag)
{
    HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);

    CONSOLE_CURSOR_INFO cursorInfo;

    GetConsoleCursorInfo(consoleHandle, &cursorInfo);
    cursorInfo.bVisible = flag; // show or hide if flag is true or false respectively
    SetConsoleCursorInfo(consoleHandle, &cursorInfo);
}


void main()
{
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    SendMessage(GetConsoleWindow(), WM_SYSKEYDOWN, VK_RETURN, 0x20000000);
    showConsoleCursor(false);
    cls();
    drawLine(25,25,50,0,255,255,0);
    cls();
    Sleep(1000);
    system("pause");
}

共1个答案

匿名用户

Windows中的绘图API需要一个设备上下文,而控制台没有任何您可以使用的设备上下文。 您不能在控制台中按您想要的方式绘制图形。

如果你想绘制简单的ascii,你可以使用像ncurses这样的库。 但是使用GDI,GDI+或(首选的)Direct2D绘图需要一个普通窗口,而不是控制台(控制台是设计用于绘制文本的子类)。

通常,在控制台中做类似的事情是徒劳的,而且不使用控制台窗口。 研究普通GUI示例,查看消息循环,WM_PAINT等。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|windows.h|头文件|试图|中|控制台|上画|一条线|但我|画出|线|闪烁)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?