简体   繁体   English

是否可以检查将程序输出重定向到文件的控制台的宽度?

[英]Is it possible to check width of a console in which the program output is redirected to a file?

GetConsoleScreenBufferInfo() returns error when initialized with standard output when program output is redirected to another command or a file. 当程序输出重定向到另一个命令或文件时,使用标准输出初始化时, GetConsoleScreenBufferInfo()返回错误。

Is there any way to get a handle to console in which the program runs and get its width no matter if program output is written on console or not ? 无论是否在控制台上编写程序输出,是否都可以通过某种方法获取运行程序的控制台并获取其宽度?

Maybe GetConsoleWindow() is here a help, but I don't know how to use handle that it produces to get the width. 也许GetConsoleWindow()在这里有帮助,但是我不知道如何使用它产生的句柄来获取宽度。

Your question makes little sense. 您的问题毫无意义。 If output is redirected then your console window width doesn't matter at all. 如果输出被重定向,则控制台窗口的宽度完全没有关系。 Only the console, if any, of the program that displays the redirected output matters. 仅显示重定向输出的程序的控制台(如果有)很重要。 You can't guess the window size of, say, Notepad. 您无法猜测记事本的窗口大小。

You can however get a handle for the console, you need to use CreateFile(): 但是,您可以获取控制台的句柄,需要使用CreateFile():

HANDLE hConsole = CreateFile(L"CONOUT$", 
    GENERIC_READ | GENERIC_WRITE,
    0, 0, OPEN_EXISTING, 0, 0);
CONSOLE_SCREEN_BUFFER_INFO info = {0};
BOOL ok = GetConsoleScreenBufferInfo(hConsole, &info);
printf("OK = %d, %d x %d\n", ok, 
    info.srWindow.Right - info.srWindow.Left + 1, 
    info.srWindow.Bottom - info.srWindow.Top + 1);

Output in redirected file: 在重定向文件中输出:

OK = 1, 80 x 25 确定= 1,80 x 25

看一下GetConsoleScreenBufferInfo ,特别是CONSOLE_SCREEN_BUFFERsrWindow成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM