应用程序控制台输出和正确编码到Delphi中的TMemo

时间:2016-05-28 17:21:40

标签: delphi encoding console-application

我从其他statckoverflow获得下面列出的函数。

我有重音字符的编码问题,以便在TMemo中显示结果。 如果我使用的样品:

Memo1.Text := GetDosOutput('Help DIR');

我的Memo1.Text显示:

"Exibe uma lista de arquivos e subdiret¢rios em um diret¢rio.
 DIR [unidade:][caminho][arquivo] [/A[[:]atributos]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]ordem_de_classifica‡Æo]] [/P] [/Q] [/R] [/S] [/T[[:]campo_de_tempo]]
  [/W] [/X] [/4]
  .......
"

请问,如何将函数的结果字符串转换为在TMemo中正确显示?

我试过

Memo1.Text := UnicodeString(GetDosOutput('Help DIR'));

但是,不要看。

function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
var
  SA: TSecurityAttributes;
  SI: TStartupInfo;
  PI: TProcessInformation;
  StdOutPipeRead, StdOutPipeWrite: THandle;
  WasOK: Boolean;
  Buffer: array[0..255] of AnsiChar;
  BytesRead: Cardinal;
  WorkDir: string;
  Handle: Boolean;
begin
  Result := '';
  with SA do begin
    nLength := SizeOf(SA);
    bInheritHandle := True;
    lpSecurityDescriptor := nil;
  end;
  CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
  try
    with SI do
    begin
      FillChar(SI, SizeOf(SI), 0);
      cb := SizeOf(SI);
      dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
      wShowWindow := SW_HIDE;
      hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
      hStdOutput := StdOutPipeWrite;
      hStdError := StdOutPipeWrite;
    end;
    WorkDir := Work;
    Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
                            nil, nil, True, 0, nil,
                            PChar(WorkDir), SI, PI);
    CloseHandle(StdOutPipeWrite);
    if Handle then
      try
        repeat
          WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
          if BytesRead > 0 then
          begin
            Buffer[BytesRead] := #0;
            Result :=Result + Buffer;
          end;
        until not WasOK or (BytesRead = 0);
        WaitForSingleObject(PI.hProcess, INFINITE);
      finally
        CloseHandle(PI.hThread);
        CloseHandle(PI.hProcess);
      end;
  finally
    CloseHandle(StdOutPipeRead);
  end;
end;

1 个答案:

答案 0 :(得分:1)

从J ..建议,我创建了StrOemToAnsi函数,显示如下使用 OemToCharBuffA。

为了测试我做了:

procedure Tfm_nh_maindicom.Button1Click(Sender: TObject);
var s:string;
    function StrOemToAnsi(const aStr : AnsiString) : AnsiString;
    var
      Len : Integer;
    begin
      if aStr = '' then Exit;
      Len := Length(aStr);
      SetLength(Result, Len);
      OemToCharBuffA(PAnsiChar(aStr), PAnsiChar(Result), Len);
    end;
begin
  S:=GetDosOutput('Help DIR');
  Memo1.Text:=StrOemToAnsi(s);
end;

Memo1的结果是:

"Exibe uma lista de arquivos e subdiretórios em um diretório.

DIR [unidade:][caminho][arquivo] [/A[[:]atributos]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]ordem_de_classificação]] [/P] [/Q] [/R] [/S] [/T[[:]campo_de_tempo]]
  [/W] [/X] [/4]
....
"