如何检查我的 Delphi 控制台应用程序是否重定向到文件或管道? [英] How do I check if my Delphi console app is redirected to a file or pipe?

查看:20
本文介绍了如何检查我的 Delphi 控制台应用程序是否重定向到文件或管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序,当输出重定向(外部)到文件或管道(myapp.exe > Foo.bar)时,它必须禁用或启用某些操作

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)

如何检查我的 Delphi 控制台应用程序是否被重定向到文件或管道?

How I can check if my Delphi console app is redirected to a file or pipe?

推荐答案

您可以使用 GetStdHandleGetFileType 函数.

you can use the GetStdHandle and GetFileType functions.

首先使用 GetStdHandle 函数检索控制台输出句柄,然后可以使用 GetFileType 函数检查句柄的类型.

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.

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows,
  SysUtils;


function ConsoleRedirected: Boolean;
var
  FileType : DWORD;
begin
  FileType:= GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
  Result  := (FileType=FILE_TYPE_PIPE) or (FileType=FILE_TYPE_DISK);
end;


begin
  try
    if ConsoleRedirected then
      Writeln('Hello From File')
    else
      Writeln('Hello Console');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

这篇关于如何检查我的 Delphi 控制台应用程序是否重定向到文件或管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆