一,背景描述
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,函数列表
还有其它函数没有列出,以后有空再加函数名 | 功能描述 |
AddConsoleAlias | Defines a console alias for the specified executable. |
AllocConsole | Allocates a new console for the calling process. |
AttachConsole | Attaches the calling process to the console of the specified process. |
CreateConsoleScreenBuffer | Creates a console screen buffer. |
FillConsoleOutputAttribute | Sets the text and background color attributes for a specified number of character cells. |
FillConsoleOutputCharacter | Writes a character to the console screen buffer a specified number of times. |
FlushConsoleInputBuffer | Flushes the console input buffer. |
FreeConsole | Detaches the calling process from its console. |
GenerateConsoleCtrlEvent | Sends a specified signal to a console process group that shares the console associated with the calling process. |
GetConsoleAlias | Retrieves the specified alias for the specified executable. |
GetConsoleAliases | Retrieves all defined console aliases for the specified executable. |
GetConsoleAliasesLength | Returns the size, in bytes, of the buffer needed to store all of the console aliases for the specified executable. |
GetConsoleAliasExes | Retrieves the names of all executables with console aliases defined. |
GetConsoleAliasExesLength | Returns the size, in bytes, of the buffer needed to store the names of all executables that have console aliases defined. |
GetConsoleCP | Retrieves the input code page used by the console associated with the calling process. |
GetConsoleCursorInfo | Retrieves information about the size and visibility of the cursor for the specified console screen buffer. |
GetConsoleDisplayMode | Retrieves the display mode of the current console. |
GetConsoleFontSize | Retrieves the size of the font used by the specified console screen buffer. |
GetConsoleHistoryInfo | Retrieves the history settings for the calling process's console. |
GetConsoleMode | Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer. |
GetConsoleOriginalTitle | Retrieves the original title for the current console window. |
GetConsoleOutputCP | Retrieves the output code page used by the console associated with the calling process. |
GetConsoleProcessList | Retrieves a list of the processes attached to the current console. |
GetConsoleScreenBufferInfo | Retrieves information about the specified console screen buffer. |
GetConsoleScreenBufferInfoEx | Retrieves extended information about the specified console screen buffer. |
GetConsoleSelectionInfo | Retrieves information about the current console selection. |
GetConsoleTitle | Retrieves the title for the current console window. |
GetConsoleWindow | Retrieves the window handle used by the console associated with the calling process. |
GetCurrentConsoleFont | Retrieves information about the current console font. |
GetCurrentConsoleFontEx | Retrieves extended information about the current console font. |
GetLargestConsoleWindowSize | Retrieves the size of the largest possible console window. |
GetNumberOfConsoleInputEvents | Retrieves the number of unread input records in the console's input buffer. |
GetNumberOfConsoleMouseButtons | Retrieves the number of buttons on the mouse used by the current console. |
GetStdHandle | Retrieves a handle for the standard input, standard output, or standard error device. |
HandlerRoutine | An application-defined function used with the SetConsoleCtrlHandler function. |
PeekConsoleInput | Reads data from the specified console input buffer without removing it from the buffer. |
ReadConsole | Reads character input from the console input buffer and removes it from the buffer. |
ReadConsoleInput | Reads data from a console input buffer and removes it from the buffer. |
ReadConsoleOutput | Reads character and color attribute data from a rectangular block of character cells in a console screen buffer. |
ReadConsoleOutputAttribute | Copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer. |
ReadConsoleOutputCharacter | Copies a number of characters from consecutive cells of a console screen buffer. |
ScrollConsoleScreenBuffer | Moves a block of data in a screen buffer. |
SetConsoleActiveScreenBuffer | Sets the specified screen buffer to be the currently displayed console screen buffer. |
SetConsoleCP | Sets the input code page used by the console associated with the calling process. |
SetConsoleCtrlHandler | Adds or removes an application-defined HandlerRoutine from the list of handler functions for the calling process. |
SetConsoleCursorInfo | Sets the size and visibility of the cursor for the specified console screen buffer. |
SetConsoleCursorPosition | Sets the cursor position in the specified console screen buffer. |
SetConsoleDisplayMode | Sets the display mode of the specified console screen buffer. |
SetConsoleHistoryInfo | Sets the history settings for the calling process's console. |
SetConsoleMode | Sets the input mode of a console's input buffer or the output mode of a console screen buffer. |
SetConsoleOutputCP | Sets the output code page used by the console associated with the calling process. |
SetConsoleScreenBufferInfoEx | Sets extended information about the specified console screen buffer. |
SetConsoleScreenBufferSize | Changes the size of the specified console screen buffer. |
SetConsoleTextAttribute | Sets the foreground (text) and background color attributes of characters written to the console screen buffer. |
SetConsoleTitle | Sets the title for the current console window. |
SetConsoleWindowInfo | Sets the current size and position of a console screen buffer's window. |
SetCurrentConsoleFontEx | Sets extended information about the current console font. |
SetStdHandle | Sets the handle for the standard input, standard output, or standard error device. |
WriteConsole | Writes a character string to a console screen buffer beginning at the current cursor location. |
WriteConsoleInput | Writes data directly to the console input buffer. |
WriteConsoleOutput | Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer. |
WriteConsoleOutputAttribute | Copies a number of foreground and background color attributes to consecutive cells of a console screen buffer. |
WriteConsoleOutputCharacter | Copies 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