如何检查我的 Delphi 控制台应用程序是否重定向到文件或管道?
我有一个控制台应用程序,当输出重定向(外部)到文件或管道时(myapp.exe > Foo.bar),必须禁用或启用某些操作
我如何检查我的 Delphi 控制台应用程序是否重定向到文件或管道?
I have a console app that must disable or enable some operations when output is redirected (externally) to a file or pipe (myapp.exe > Foo.bar)
How I can check if my Delphi console app is redirected to a file or pipe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
GetStdHandle
和GetFileType
函数。首先,使用 GetStdHandle 函数检索控制台输出句柄,然后可以使用 GetFileType 函数检查句柄的类型。
you can use the
GetStdHandle
andGetFileType
functions.first you retrieve the console output handle using the GetStdHandle function and then you can check the type of the handle with the
GetFileType
function.我在这里介绍的方法感觉很老套,但我找不到更好的方法来检测标准输出是否已从屏幕控制台重定向。使用
GetFileType
的方法无法检测所有形式的重定向,因为某些重定向是针对FILE_TYPE_CHAR
类型的设备。调用
GetConsoleMode()
传递标准输出句柄。如果GetConsoleMode()
失败,则您的控制台已重定向。The approach I present here feels hacky but I can't find a better way to detect whether or not the standard output has been redirected away from a screen console. The approach using
GetFileType
cannot detect all forms of redirection since some redirections are to devices of typeFILE_TYPE_CHAR
.Call
GetConsoleMode()
passing the standard output handle. IfGetConsoleMode()
fails then your console has been redirected.