GUI应用程序添加控制台

一,背景描述

    GUI应用程序初始化时是没有控制台的,而控制台应用程序则以控制台来初始化.虽然WIN32时代是图像界面时代,但是程序中还需要用到命令行模式,比如批处理.

二,创建一个对话框的MFC程序

1,创建一个MFC对话框应用程序MFCConsole


2,在对话框上创建两个按钮CreateConsole和ExitConsole,分别添加单击事件

void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
}


void CMFCConsoleDlg::OnBnClickedButtonExitConsole()
{
	// TODO: Add your control notification handler code here
}

3,创建控制台

  在OnBnClickedButtonCreateConsole函数中创建新的控制台
void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
	if (!AllocConsole())
	{
		return ;
	}
	freopen("CONOUT$", "w", stdout); // 重定位标准输出到控制台
	printf("Debug console created.\n");
}
点击该按钮后效果如下:

4,关闭控制台

在OnBnClickedButtonExitConsole函数中退出控制台
void CMFCConsoleDlg::OnBnClickedButtonExitConsole()
{
	// TODO: Add your control notification handler code here
	FreeConsole();
}
点击该按钮后控制台退出.

至此新建一个基本的控制台完成了.需要做如下说明:
※一个进程仅能关联一个控制台,若进程已拥有控制台,则AllocConsole会失败.
※一个进程可以调用FreeConsole函数来释放之前关联的控制台,之后可以调用AllocConsole创建一个新的控制台或使用AttachConsole函数关联另一个控制台.
※如果主调用进程创建了一个子进程,则子进程也将继承这个新创建的控制台.
※可以使用CloseHandle释放控制台句柄.

三,输出文本

1,向使用printf函数向控制台输出文本

void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
	if (!AllocConsole())
	{
		return ;
	}
	freopen("CONOUT$", "w", stdout); // 重定位标准输出到控制台
	printf("Debug console created.\n");
}

2,使用WriteConsole函数向控制台输出文本

void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
	if (!AllocConsole())
	{
		return ;
	}
	freopen("CONOUT$", "w", stdout); // 重定位标准输出到控制台

	printf("printf: Debug console created.\n");

	// 获取标准输出设备句柄
	HANDLE hOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
	char szOutput[] = { "WriteConsole: Debug console created.\n"};
	WriteConsole(hOutputHandle, szOutput, sizeof(szOutput) - 1, NULL, NULL); // 字符串默认以\0结束,所以减一
}
WriteConsole函数使用说明,
WINBASEAPI
BOOL
WINAPI
WriteConsoleA(
    __in HANDLE hConsoleOutput,
    __in_ecount(nNumberOfCharsToWrite) CONST VOID *lpBuffer,
    __in DWORD nNumberOfCharsToWrite,
    __out_opt LPDWORD lpNumberOfCharsWritten,
    __reserved LPVOID lpReserved);
WINBASEAPI
BOOL
WINAPI
WriteConsoleW(
    __in HANDLE hConsoleOutput,
    __in_ecount(nNumberOfCharsToWrite) CONST VOID *lpBuffer,
    __in DWORD nNumberOfCharsToWrite,
    __out_opt LPDWORD lpNumberOfCharsWritten,
    __reserved LPVOID lpReserved);
#ifdef UNICODE
#define WriteConsole  WriteConsoleW
#else
#define WriteConsole  WriteConsoleA
#endif // !UNICODE
参数[hConsoleOutput]:标准输出句柄,使用GetStdHandle获取控制台的句柄,这里我们获取的是STD_OUTPUT_HANDLE类型.
※控制台有三种句柄STD_INPUT_HANDLE,STD_OUTPUT_HANDLE和STD_ERROR_HANDLE
参数[lpBuffer]:写出内容地址.
参数[nNumberOfCharsToWrite]:预计写出长度.
参数[lpNumberOfCharsWritten]:实际写出长度.
※可以为NULl,但不建议,BoundChecker会在这里提示错误用法.
参数[lpReserved]:系统保留,默认为NULL.
※MSDN里说也可以用WriteFile向控制台的句柄输出.

四,输入文本

1,使用WriteConsole获取用户输入

void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
	
	if (!AllocConsole())
	{
		return ;
	}
	
	freopen("CONOUT$", "w", stdout); // 重定位标准输出到控制台
	printf("printf: Debug console created.\n");

	// 获取标准输出设备句柄
	HANDLE hOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
	char szOutput[] = { "WriteConsole: Debug console created.\n"};
	WriteConsole(hOutputHandle, szOutput, sizeof(szOutput) - 1, NULL, NULL); // 字符串默认以\0结束,所以减一

	TCHAR szBuffer[100] = { 0 };	// 开缓存区
	DWORD dwCount = 0;		// 已输入数
	HANDLE hdlRead = GetStdHandle(STD_INPUT_HANDLE);
	ReadConsole(hdlRead, szBuffer, 100, &dwCount, NULL);
}
※WriteConsole函数第四个参数必须指定,否则会无法读取.
※MSDN里还提到,若需要获取其它键盘外的输入信息,如鼠标信息,只能使用ReadConsoleInput函数:If the input buffer contains input events other than keyboard events (such as mouse events or window-resizing events), they are discarded. Those events can only be read by using the ReadConsoleInput function.

五,其他函数

1,获取控制台标题

char strTitle[255]; 
GetConsoleTitle(strTitle, 255); // 获取窗口标题 

2,修改控制台标题

SetConsoleTitle("MFC控制台"); // 设置控制台标题

3,设置文本前景色和背景色颜色

SetConsoleTextAttribute(hOutputHandle, FOREGROUND_RED | BACKGROUND_GREEN);

4,创建控制台屏幕缓冲区

void CMFCConsoleDlg::OnBnClickedButtonCreateConsole()
{
	// TODO: Add your control notification handler code here
	if (!AllocConsole())
	{
		return ;
	}
	
	// 重定位标准输出到控制台
	freopen("CONOUT$", "w", stdout);

	// 获取标准输出设备句柄
	HANDLE hOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);

	char szOutput[] = { "hOutputHandle: Debug console created.\n"};
	// 字符串默认以\0结束,所以减一
	WriteConsole(hOutputHandle, szOutput, sizeof(szOutput) - 1, NULL, NULL);

	// 新建屏幕缓冲区,一个进程可以有多个屏幕缓冲区
	HANDLE hNewOutputConsoleHandle = CreateConsoleScreenBuffer(
		GENERIC_READ | GENERIC_WRITE,		//权限    
		FILE_SHARE_READ | FILE_SHARE_WRITE, // 控制台的共享方式    
		NULL,								// 安全性设置,NULL默认即可    
		CONSOLE_TEXTMODE_BUFFER,			// 唯一值    
		NULL								// 保留    
		);
	char szNewOutput[] = { "hNewOutputConsoleHandle: Debug console created.\n"};
	WriteConsole(hNewOutputConsoleHandle, szNewOutput, sizeof(szNewOutput) - 1, NULL, NULL);

	TCHAR szBuffer[100] = { 0 };	// 开缓存区
	DWORD dwCount  = 0;				// 已输入数
	// 此处读到默认缓冲区
	ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, 100, &dwCount, NULL);

	// 显示该新建缓冲区的内容
	SetConsoleActiveScreenBuffer(hNewOutputConsoleHandle);

	// 在新建缓冲区从键盘获取一段文字
	ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, 100, &dwCount, NULL);

	// 显示默认缓冲区
	SetConsoleActiveScreenBuffer(hOutputHandle);
}
该函数演示了默认缓冲区和新建缓冲区之间的切换过程.

5,设置控制台文本字体

CONSOLE_FONT_INFOEX cfi;
cfi.cbSize = sizeof cfi;
cfi.nFont = 0;
cfi.dwFontSize.X = 0;
cfi.dwFontSize.Y = 16;
cfi.FontFamily = FF_DONTCARE;
cfi.FontWeight = FW_MEDIUM;
wcscpy_s(cfi.FaceName, L"Consolas");
SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);

7,函数列表

还有其它函数没有列出,以后有空再加
控制台函数列表
函数名功能描述
AddConsoleAliasDefines a console alias for the specified executable.
AllocConsoleAllocates a new console for the calling process.
AttachConsoleAttaches the calling process to the console of the specified process.
CreateConsoleScreenBufferCreates a console screen buffer.
FillConsoleOutputAttributeSets the text and background color attributes for a specified number of character cells.
FillConsoleOutputCharacterWrites a character to the console screen buffer a specified number of times.
FlushConsoleInputBufferFlushes the console input buffer.
FreeConsoleDetaches the calling process from its console.
GenerateConsoleCtrlEventSends a specified signal to a console process group that shares the console associated with the calling process.
GetConsoleAliasRetrieves the specified alias for the specified executable.
GetConsoleAliasesRetrieves all defined console aliases for the specified executable.
GetConsoleAliasesLengthReturns the size, in bytes, of the buffer needed to store all of the console aliases for the specified executable.
GetConsoleAliasExesRetrieves the names of all executables with console aliases defined.
GetConsoleAliasExesLengthReturns the size, in bytes, of the buffer needed to store the names of all executables that have console aliases defined.
GetConsoleCPRetrieves the input code page used by the console associated with the calling process.
GetConsoleCursorInfoRetrieves information about the size and visibility of the cursor for the specified console screen buffer.
GetConsoleDisplayModeRetrieves the display mode of the current console.
GetConsoleFontSizeRetrieves the size of the font used by the specified console screen buffer.
GetConsoleHistoryInfoRetrieves the history settings for the calling process's console.
GetConsoleModeRetrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
GetConsoleOriginalTitleRetrieves the original title for the current console window.
GetConsoleOutputCPRetrieves the output code page used by the console associated with the calling process.
GetConsoleProcessListRetrieves a list of the processes attached to the current console.
GetConsoleScreenBufferInfoRetrieves information about the specified console screen buffer.
GetConsoleScreenBufferInfoExRetrieves extended information about the specified console screen buffer.
GetConsoleSelectionInfoRetrieves information about the current console selection.
GetConsoleTitleRetrieves the title for the current console window.
GetConsoleWindowRetrieves the window handle used by the console associated with the calling process.
GetCurrentConsoleFontRetrieves information about the current console font.
GetCurrentConsoleFontExRetrieves extended information about the current console font.
GetLargestConsoleWindowSizeRetrieves the size of the largest possible console window.
GetNumberOfConsoleInputEventsRetrieves the number of unread input records in the console's input buffer.
GetNumberOfConsoleMouseButtonsRetrieves the number of buttons on the mouse used by the current console.
GetStdHandleRetrieves a handle for the standard input, standard output, or standard error device.
HandlerRoutineAn application-defined function used with the SetConsoleCtrlHandler function.
PeekConsoleInputReads data from the specified console input buffer without removing it from the buffer.
ReadConsoleReads character input from the console input buffer and removes it from the buffer.
ReadConsoleInputReads data from a console input buffer and removes it from the buffer.
ReadConsoleOutputReads character and color attribute data from a rectangular block of character cells in a console screen buffer.
ReadConsoleOutputAttributeCopies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer.
ReadConsoleOutputCharacterCopies a number of characters from consecutive cells of a console screen buffer.
ScrollConsoleScreenBufferMoves a block of data in a screen buffer.
SetConsoleActiveScreenBufferSets the specified screen buffer to be the currently displayed console screen buffer.
SetConsoleCPSets the input code page used by the console associated with the calling process.
SetConsoleCtrlHandlerAdds or removes an application-defined HandlerRoutine from the list of handler functions for the calling process.
SetConsoleCursorInfoSets the size and visibility of the cursor for the specified console screen buffer.
SetConsoleCursorPositionSets the cursor position in the specified console screen buffer.
SetConsoleDisplayModeSets the display mode of the specified console screen buffer.
SetConsoleHistoryInfoSets the history settings for the calling process's console.
SetConsoleModeSets the input mode of a console's input buffer or the output mode of a console screen buffer.
SetConsoleOutputCPSets the output code page used by the console associated with the calling process.
SetConsoleScreenBufferInfoExSets extended information about the specified console screen buffer.
SetConsoleScreenBufferSizeChanges the size of the specified console screen buffer.
SetConsoleTextAttributeSets the foreground (text) and background color attributes of characters written to the console screen buffer.
SetConsoleTitleSets the title for the current console window.
SetConsoleWindowInfoSets the current size and position of a console screen buffer's window.
SetCurrentConsoleFontExSets extended information about the current console font.
SetStdHandleSets the handle for the standard input, standard output, or standard error device.
WriteConsoleWrites a character string to a console screen buffer beginning at the current cursor location.
WriteConsoleInputWrites data directly to the console input buffer.
WriteConsoleOutputWrites character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
WriteConsoleOutputAttributeCopies a number of foreground and background color attributes to consecutive cells of a console screen buffer.
WriteConsoleOutputCharacterCopies a number of characters to consecutive cells of a console screen buffer.

MSN中函数说明:https://msdn.microsoft.com/en-us/library/ms682073(v=vs.85).aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值