简体   繁体   中英

How can I run a cmd command in delphi?

I'm trying to run a cmd command in delphi and have tried

ShellExecute(Handle, 'runas', 'cmd.exe', ' net start ExportFileMainService', nil, SW_SHOWNORMAL);

but it doesn't seem to be working and I'm not sure why.

Here is some code I wrote in Delphi 2010 to open a command prompt:

function TForm7.RunCmdAndWait(hWnd: HWND; aParameters: string):
    Cardinal;
var
  sei: TShellExecuteInfo;
  aFile, dir: string;
begin
  Result := 0;
  dir := ExtractFilePath(Application.ExeName);
  SetCurrentDir(dir);
  FillChar(sei, SizeOf(sei), 0);
  sei.cbSize := SizeOf(sei);
  sei.Wnd := hWnd;
  sei.fMask := {SEE_MASK_FLAG_NO_UI or} SEE_MASK_NOCLOSEPROCESS;
  sei.lpVerb := 'open';
  aFile := 'cmd';
  sei.lpFile := PChar(aFile);
  sei.lpParameters := PChar(aParameters);
  sei.lpDirectory := PChar(dir);
  sei.nShow := SW_SHOWNORMAL;

  if not ShellExecuteEx(@sei) then
  begin
    RaiseLastOSError;
  end;
  if sei.hProcess <> 0 then
  begin
    while WaitForSingleObject(sei.hProcess, 250) = WAIT_TIMEOUT do
      Application.ProcessMessages;
    GetExitCodeProcess(sei.hProcess, Result);
    CloseHandle(sei.hProcess);
  end else
    TaskMessageDlg('Error running program!', 'No handle to process.',
      mtError, [mbOK], 0);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM