How do I open a file with the default text editor?

后端 未结 3 1179
盖世英雄少女心
盖世英雄少女心 2020-12-18 13:11

I want to open a *.conf file. I want to open this file with the standard Windows editor (e.g., notepad.exe).

I currently have this ShellExecute code:



        
相关标签:
3条回答
  • 2020-12-18 13:24

    use

    ShellExecute(0, 'Open', PChar(AFile), nil, '', 1{SW_SHOWNORMAL});
    

    in Delphi DX10 this function defined in

    Winapi.ShellAPI

    0 讨论(0)
  • 2020-12-18 13:33

    How do I open a file with the default text editor?

    You need to use ShellExecuteEx and use the lpClass member of SHELLEXECUTEINFO to specify that you want to treat the file as a text file. Like this:

    procedure OpenAsTextFile(const FileName: string);
    var
      sei: TShellExecuteInfo;
    begin
      ZeroMemory(@sei, SizeOf(sei));
      sei.cbSize := SizeOf(sei);
      sei.fMask := SEE_MASK_CLASSNAME;
      sei.lpFile := PChar(FileName);
      sei.lpClass := '.txt';
      sei.nShow := SW_SHOWNORMAL;
      ShellExecuteEx(@sei);
    end;
    

    Pass the full path to the file as FileName.

    0 讨论(0)
  • 2020-12-18 13:40

    The main problem is that you use nginx.conf as the file name. You need the fully-qualified file name (with drive and directory). If the file resides in the same directory as your EXE, you should do

    ShellExecute(Handle, nil,
      PChar(ExtractFilePath(Application.ExeName) + 'nginx.conf'),
      nil, nil, SW_SHOWNORMAL)
    

    There is no need to set the directory, and you should normally use SW_SHOWNORMAL.

    Also, this only works if the system running the application has the file associations set up properly for .conf files. If the system running the application opens .conf files with MS Paint, then the line above will start MS Paint. If there are no associations at all, the line won't work.

    You can specify manually to use notepad.exe:

    ShellExecute(Handle, nil, PChar('notepad.exe'),
      PChar(ExtractFilePath(Application.ExeName) + 'nginx.conf'),
      nil, SW_SHOWNORMAL)
    

    Now we start notepad.exe and pass the file name as the first argument.

    Third, you shouldn't use try..except the way you do now. The ShellExecute may fail for other reasons than 'invalid config path', and in any case, it won't raise an exception. Instead, consider

    if FileExists(...) then
      ShellExecute(...)
    else
      MessageBox(Handle, 'Invalid path to configuration file', 'Error', MB_ICONERROR)
    

    Now, back to the main issue. My first code snippet only works if the system running your application happens to have an appropriate file association post for .conf files, while the second will always open Notepad. A better alternative might be to use the application used to open .txt files. David's answer gives an example of this.

    0 讨论(0)
提交回复
热议问题