如何多次调用initgraph?

时间:2019-01-21 17:20:00

标签: c bgi

请查看以下代码:

#include <stdio.h>
#include <graphics.h>
#include <conio.h>
using namespace std;
void drawrect()
{
    int gdriver = IBM8514, gmode;
    initgraph(&gdriver, &gmode, "");
    rectangle(500, 500, 700, 700);
    getch();
    cleardevice();
    closegraph();
}
int main()
{
    int f=1;
    while(f)
    {
        char c;
        printf("Press \"e\" to end, and any other character to draw a rectangle");
        scanf("%c",&c);
        c=='e' ? f=0:f=1;
        drawrect();
        fflush(stdin);
    }
}

在我第一次运行该程序时,它可以正常工作并绘制一个矩形,但是第一次后,矩形功能将不起作用,并且GUI屏幕完全空白,而我已经清除并关闭了上一个图形

那为什么第二次不起作用?

2 个答案:

答案 0 :(得分:1)

您的代码具有未定义的行为。致电initgraph

int gdriver = IBM8514, gmode;
initgraph(&gdriver, &gmode, "");

应将指针传递到您要使用的图形模式。 This page描述了该函数及其参数,并描述了该模式:

  

* graphmode是指定初始图形模式的整数(除非* graphdriver等于DETECT;在这种情况下,将设置* graphmode   通过initgraph达到检测到的最高分辨率   驱动程序)。您可以使用以下常量给* graphmode一个值   graphics_modes枚举类型,在graphics.h和   列在下面。

     

graphdriver和graphmode必须从   下表,否则您将获得无法预测的结果。例外   是graphdriver = DETECT。

但是您尚未设置模式,如引用的第二段所述,结果是不可预测的。这可以是:按照您的预期工作,而不是工作,工作异常或油炸处理器。

因此,您可以设置要使用的图形模式

int gdriver = IBM8514, gmode = 0;

或您需要使用的任何模式。或者,您可以告诉系统自行检测,在这种情况下,您可以使用

int gdriver = DETECT, gmode;

答案 1 :(得分:0)

Init和close应该只被调用一次,而不是在drawrect中调用,而通常在主调用中被调用...在渲染例程中使用getch也没有意义...

我不会在您的代码中碰到其他问题,因为我已经多年没有编写控制台了,而 BGI 的时间甚至更长,但是我将首先对代码进行重新排序:

#include <stdio.h>
#include <graphics.h>
#include <conio.h>
using namespace std;
void drawrect()
{
    rectangle(500, 500, 700, 700);
}
int main()
{
    int f=1;

    int gdriver = IBM8514, gmode;
    initgraph(&gdriver, &gmode, "");

    while(f)
    {
        char c;
        printf("Press \"e\" to end, and any other character to draw a rectangle");
        scanf("%c",&c);
        c=='e' ? f=0:f=1;
        drawrect();
        getch();
        fflush(stdin);
    }

    cleardevice();
    closegraph();
}

将来还会用其真实名称 BGI 来寻址该库,因为graphics.h没有意义,因为几乎所有gfx api / lib都获得了一个具有该名称的文件...