4. 使用UEFI控制台输出

任务目标

本案例将编写一个UEFI应用程序,通过标准控制台输出接口ConOut实现格式化字符串输出,并演示文本前景色与背景色的设置方法。程序启动后依次输出普通文本、格式化变量内容以及带颜色的提示信息,最终等待用户按键后退出。

环境与依赖

  • EDK2开发环境(已配置好OVMF或真实UEFI固件运行平台)
  • 使用StdLib中的Print库函数(通过UefiLib封装)
  • 无需额外硬件依赖,仅使用UEFI标准协议

核心实现

以下代码完整实现了目标功能。程序入口接收ImageHandle和SystemTable,通过系统表获取ConOut接口,调用Print函数输出格式化字符串,并使用SetAttribute控制颜色。

#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/PrintLib.h>

EFI_STATUS
EFIAPI
UefiMain (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *ConOut;
  UINTN   Index;
  UINT32  OriginalAttribute;

  // 获取控制台输出协议
  ConOut = SystemTable->ConOut;

  // 保存原始颜色属性,便于退出时恢复
  OriginalAttribute = ConOut->Mode->Attribute;

  // 1. 输出普通字符串
  ConOut->OutputString (ConOut, L"Hello, UEFI Console!\r\n");

  // 2. 输出格式化字符串(使用PrintLib中的Unicode格式化函数)
  Print (L"System table address: 0x%p\r\n", (VOID *)SystemTable);
  Print (L"ConOut mode: %d columns x %d rows\r\n",
         ConOut->Mode->MaxMode,
         ConOut->Mode->Mode);

  // 3. 演示颜色控制:设置白底蓝字
  ConOut->SetAttribute (ConOut, EFI_TEXT_ATTR (EFI_BLUE, EFI_WHITE));
  ConOut->OutputString (ConOut, L"Blue text on white background\r\n");

  // 4. 演示颜色控制:设置黑底红字
  ConOut->SetAttribute (ConOut, EFI_TEXT_ATTR (EFI_RED, EFI_BLACK));
  ConOut->OutputString (ConOut, L"Red text on black background\r\n");

  // 5. 恢复原始颜色属性
  ConOut->SetAttribute (ConOut, OriginalAttribute);

  // 6. 输出循环计数值,演示整数格式化
  for (Index = 0; Index < 3; Index++) {
    Print (L"Loop iteration: %d\r\n", Index);
  }

  // 等待用户按键后退出
  Print (L"Press any key to exit...\r\n");
  SystemTable->ConIn->Reset (SystemTable->ConIn, FALSE);
  {
    EFI_INPUT_KEY  Key;
    EFI_STATUS     Status;
    do {
      Status = SystemTable->ConIn->ReadKeyStroke (SystemTable->ConIn, &Key);
    } while (Status == EFI_NOT_READY);
  }

  return EFI_SUCCESS;
}

编译与运行

  1. 将上述代码保存为ConsoleOutput.c,放入EDK2工程目录(如OvmfPkg/Applications/ConsoleOutput/)。
  2. 在对应.inf文件中声明源文件与依赖库:
[Sources]
  ConsoleOutput.c

[LibraryClasses]
  UefiLib
  UefiBootServicesTableLib
  PrintLib
  1. 使用build命令编译生成ConsoleOutput.efi。
  2. 在UEFI Shell中运行:fs0:\ConsoleOutput.efi

验证方法

程序运行后,屏幕应依次显示以下内容,且颜色变化符合代码设定:

  • 第一行白色文本:Hello, UEFI Console!
  • 两行格式化输出,分别显示系统表地址和控制台模式信息(具体数值取决于运行环境)
  • 白底蓝字一行、黑底红字一行
  • 三行循环计数(0、1、2)
  • 最后提示按键退出,按任意键后程序返回Shell

若所有输出顺序、颜色与上述描述一致,且程序能正常退出,则判定案例通过。注意:系统表地址和模式数值因平台而异,只需确认格式正确即可。