首页 > 解决方案 > 获取对话框中dialog_menu的选择索引(libdialog)

问题描述

我正在使用dialogC 实现一个小型对话系统,并且一直在阅读此处的文档,但无法弄清楚如何获取dialog_menu命令的选择索引。

我知道该init_dialog(FILE *, FILE *)函数在stdout这里作为输出,但是我不相信无论如何都可以将输出重定向到变量。

运行此代码时,按“退出”按钮返回代码 1,同时按两个选项中的任何一个返回 0。如何区分这些选择?

#include <dialog.h>
#include <stdio.h>
#include <stdlib.h>

#define LEN(arr) ((int) (sizeof(arr) / sizeof(arr)[0]))

int
menu()
{
    int select;
    char *modes[] =
    {
        "1", "The first option",
        "2", "The second option"
    };

    init_dialog(stdin, stdout);
    select = dialog_menu("test_app", "Choose an option.", 0, 0, 0, LEN(modes) / 2, modes);
    end_dialog();

    return select;
}

int
main()
{
    int status;
    status = menu();
    printf("%d\n", status);
    return status;
}

标签: cdialogstdoutncurses

解决方案


dialog库包含一个名为的结构dialog_vars,其中包含一个变量char *input_result

在菜单中进行选择时,input_result将其设置为tag的值,(在提供的源代码中,此标记是"1"或者"2",如果根本没有进行选择,则为NULL指针。

从这里,strcmp可以确定选择了哪个响应。

PS:始终确保dlg_clr_result()在重复对话之前调用,因为选择被连接input_result,因此通过不调用函数,新结果将附加到旧结果而不是替换它。

例子:

#include <dialog.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN(arr) ((int) (sizeof(arr) / sizeof(arr)[0]))

void
menu()
{
    char *modes[] =
    {
        "1", "The first option",
        "2", "The second option"
    };

    init_dialog(stdin, stdout);
    dialog_menu("test_app", "Choose an option.", 0, 0, 0, LEN(modes) / 2, modes);
    end_dialog();

    char *result = dialog_vars.input_result; /* this will be "1", "2" or NULL */

    init_dialog(stdin, stdout);
    dialog_menu("test_app", strcmp(result, "1") ? "One" : "Two", 0, 0, 1);
    end_dialog();
}

int
main()
{
    menu();
    return 0;
}

推荐阅读