点击按钮时如何打开Windows资源管理器?

10

我有一个Delphi项目里的表单,表单上有一个按钮。当用户点击这个按钮时,我想要打开Windows资源管理器。

我应该使用哪些代码来实现这个功能?

6个回答

29

如果你需要在资源管理器中选择某个特定的文件,我有以下函数可供使用:

procedure SelectFileInExplorer(const Fn: string);
begin
  ShellExecute(Application.Handle, 'open', 'explorer.exe',
    PChar('/select,"' + Fn+'"'), nil, SW_NORMAL);
end;

你可以称之为:

SelectFileInExplorer('C:\Windows\notepad.exe');

编辑:如上所述,必须将ShellAPI添加到您的uses列表中


应该使用PWideChar而不是PChar吗? - Leonardo Herrera
"explore" 作为文件夹的动词使用,而 nil 则是默认值(即文件夹的 Windows 资源管理器)。这个函数的传统名称是 OpenFileDefaultViewer(),你可以通过谷歌搜索了解更多(更适用于“打开”而不是“浏览”)。它应该也适用于任何文件类型,基于文件扩展名在注册表中的映射(例如 readme.txt --> 记事本)。要注意应用程序的假设;如果没有窗口(例如命令行或 DLL),则可以将 0 作为无效句柄传递。我认为句柄更多地涉及到 Windows 管理活动窗口和窗口所有权。 - FreeText

13

在Mason Wheeler所说的基础上,你还可以将一个目录作为参数传入,以打开窗口到一个非默认位置:

uses
  ShellAPI;

...

  ShellExecute(Application.Handle,
    nil,
    'explorer.exe',
    PChar('c:\'), //wherever you want the window to open to
    nil,
    SW_NORMAL     //see other possibilities by ctrl+clicking on SW_NORMAL
    );

8

试试这个:

ShellExecute(Application.Handle, nil, 'explorer.exe', nil, nil, SW_NORMAL);

您需要在uses子句中添加ShellAPI


3

1
在FireMonkey中,要打开选择文件的资源管理器:
uses
  Winapi.Windows,
  Winapi.ShellAPI,
  FMX.Forms,
  FMX.Platform.Win;

procedure OpenExplorerSelectingFile(const AFileName: string);
begin
  ShellExecute(WindowHandleToPlatform(Application.MainForm.Handle).Wnd, 'open', 'explorer.exe', PChar('/select,"' + AFilename + '"'), nil, SW_NORMAL);
end;

0

正如我在这里已经回答过的那样,如果您想要:

  • 在资源管理器中选择文件夹
  • 或者打开它并使用资源管理器显示其内容

我使用以下函数:

uses Winapi.ShellAPI;

procedure SelectFileOrFolderInExplorer(const sFilename: string);
begin
  ShellExecute(Application.Handle, 'open', 'explorer.exe',
    PChar(Format('/select,"%s"', [sFilename])), nil, SW_NORMAL);
end;

procedure OpenFolderInExplorer(const sFoldername: string);
begin
  ShellExecute(Application.Handle, nil, PChar(sFoldername), nil, nil, sw_Show);
end;

procedure ExecuteFile(const sFilename: string);
begin
  ShellExecute(Application.Handle, nil, PChar(sFilename), nil, nil, sw_Show);
end;

使用方法:

SelectFileOrFolderInExplorer('C:\Windows');
SelectFileOrFolderInExplorer('C:\Windows\notepad.exe');
OpenFolderInExplorer('C:\Windows');
ExecuteFile('C:\MyTextFile.txt');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接