3
我如何獲得appdata文件夾路徑?這個ID我的代碼:如何在delphi中獲取appdata文件夾路徑
begin
Winexec(PAnsichar('%appdata%\TEST.exe'), sw_show);
end;
end.
但不工作。
我如何獲得appdata文件夾路徑?這個ID我的代碼:如何在delphi中獲取appdata文件夾路徑
begin
Winexec(PAnsichar('%appdata%\TEST.exe'), sw_show);
end;
end.
但不工作。
您無法將環境變量傳遞到WinExec()
。你必須先解決這些問題:
uses
..., SysUtils;
function GetPathToTestExe: string;
begin
Result := SysUtils.GetEnvironmentVariable('APPDATA');
if Result <> '' then
Result := IncludeTrailingPathDelimiter(Result) + 'TEST.exe';
end;
uses
..., Windows;
var
Path: string;
begin
Path = GetPathToTestExe;
if Path <> '' then
WinExec(PAnsiChar(Path), SW_SHOW);
end;
或者:
uses
..., SysUtils, Windows;
function GetPathToTestExe: string;
var
Path: array[0..MAX_PATH+1] of Char;
begin
if ExpandEnvironmentStrings('%APPDATA%', Path, Length(Path)) > 1 then
Result := IncludeTrailingPathDelimiter(Path) + 'TEST.exe'
else
Result := '';
end;
更可靠的(和官方)的方式來獲得AppData文件夾路徑是使用SHGetFolderPath()
(或在Vista +上爲SHGetKnownFolderPath()
)代替:
uses
..., SysUtils, Windows, SHFolder;
function GetPathToTestExe: string;
var
Path: array[0..MAX_PATH] of Char;
begin
if SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, Path) = S_OK then
Result := IncludeTrailingPathDelimiter(Path) + 'TEST.exe'
else
Result := '';
end;
但是,在任何情況下,WinExec()
已自Windows 95過時,你真的應該使用CreateProcess()
代替:
uses
..., Windows;
var
Path: String;
si: TStartupInfo;
pi: TProcessInformation;
Path := GetPathToTetExe;
if Path <> '' then
begin
ZeroMemory(@si, SizeOf(si));
si.cb := SizeOf(si);
si.dwFlags := STARTF_USESHOWWINDOW;
si.wShowWindow := SW_SHOW;
if CreateProcess(nil, PChar(Path), nil, nil, FALSE, 0, nil, nil, @si, pi)
begin
//...
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
end;
end;