AllocConsole()

AllocConsole() 为 Windows 程序创建一个控制台窗口, 失败返回零, 可调用 GetLastError().

分配控制台后可能需要重定向标准输出和标准输入(Windows 平台标准错误和标准输出相同),

这时就需要两个特殊的文件名了:

  CONOUT$     --Console output

  CONIN$      --Console input

使用 OpenFile() 或者 VC++ 提供的 C I/O 函数来操练它们吧!

如果使用 Unicode 字符集, 可能需要设置控制台的代码页或者设置 VC++ 运行时的 Unicode 字符的映射目标字符编码:

  system("chcp 65001"); // 设置控制台使用 UTF-8 编码映射代码页

  const char *infoSetCodePage = setlocale(LC_CTYPE, ""); // 自动设置目标字符集为系统默认代码页

总之控制台对于国际化十分不友好, 不要太依靠它!

代码

//#pragma comment(lib, "d3d9.lib") 

#include <Windows.h>
#include <stdio.h>
#include <tchar.h>
#include <locale.h>

int CALLBACK _tWinMain(
	_In_ HINSTANCE hInstance,
	_In_opt_ HINSTANCE hPrevInstance,
	_In_ LPTSTR     lpCmdLine,
	_In_ int       nCmdShow
) {
	// 分配控制台,并使用特殊文件名"CONOUT$"重新打开输入流stdout: FILE *
	AllocConsole();
	FILE* file = NULL;
	freopen_s(&file, "CONOUT$", "w+", stdout);

	//system("chcp 65001");
	const char* infoSetCodePage = setlocale(LC_CTYPE, "");
	_tprintf(TEXT("设置结果:%S.\n"), infoSetCodePage);
	_tprintf(TEXT("%s, World!\n"), TEXT("你好"));

	Sleep(4000);
	FreeConsole(); // Free the console
	return 0;
}
posted @ 2018-06-01 22:37  develon  阅读(1915)  评论(0编辑  收藏  举报