tags:

views:

119

answers:

3

Hi all

I am working with Delphi 2010 and the ShellAPI. I need a little help as the program I am building grows. Here is the jest of the application:

Checks to see if a certain condition exists If said condition exists it begins to execute 2 shell commands which are dependent on the previous one executing

   uses
  ShellApi;

procedure RenameDir(DirFrom, DirTo: string);
var
  shellinfo: TSHFileOpStruct;
begin
  with shellinfo do
  begin
    Wnd    := 0;
    wFunc  := FO_RENAME;
    pFrom  := PChar(DirFrom);
    pTo    := PChar(DirTo);
    fFlags := FOF_FILESONLY or FOF_ALLOWUNDO or
              FOF_SILENT or FOF_NOCONFIRMATION;
  end;
  SHFileOperation(shellinfo);
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  RenameDir('C:\Dir1', 'C:\Dir2');

  RenameDir('C:\Dir3', 'C:\Dir');


end;

I am a novice at Delphi but I can see the issue, the second command is executing before the previous command completes. How do I solve this issue so that the first command executes and finishes before the second one is called?

UPDATE: I added the full pseudo code so that it shows what I attempting to do.

A: 

Two simple ways to do this:

  1. Insert a Sleep(X); command between the two and fill in the x with something low like 5 or 10 (should be all the ms you need).
  2. Insert an Application.ProcessMessages command between the two to allow other events including the renaming to complete.
Tom
Neither of these will necessarily work if the rename is happening asynchronously, which appears to be the case.
Mason Wheeler
Mason this is what is what is happening. Any idea how to fix it?
JamesW
I have tried the application.processmessages command and it still has the same issue
JamesW
+2  A: 

If the command you use is external command/program, consider use CreateProcess() and passing INFINITE to WaitForSingleObject(). Look at the ExecAndWait() example here.

Vantomex
@JamesW, I guess, you are currently using `SHFileOperation()` to rename directory, right? Why don't you use `MoveFile()` instead? `MoveFile()` already works asynchronously, it is faster, and you don't have to be bother with your current problem.
Vantomex
Yes Vantomex I am using SHFileOperation. I will try the MoveFile option
JamesW
Vantomex the MoveFile option was exactly what I needed. I have tested it and have a 100% working APP at this point. Thank you for being able to decipher my very vague description and help me solve this issues.
JamesW
A: 

Maybe you could use SHChangeNotifyRegister() to be notified when the directory name is actually changed.

ldsandon