views:

230

answers:

3

I've got a routine that deletes a folder and everything in it. After deleting all the files, the last thing it does is:

if not Windows.RemoveDirectory(pname) then
  raise EInOutError.Create(SysErrorMessage(GetLastError));

Unfortunately, I tend to get an error from this if I have an open window in Windows Explorer displaying the folder. The error says the folder is not empty, which is not true. Is there any way to override this, perhaps forcing the window to close?

In case it makes a difference, I'm on Vista Home Premium 64.

+1  A: 

The following code shows the general approach for closing windows. This example is for Internet Explorer; you'll have to tweak it a bit for Windows Explorer..

program Sample;

function CloseIEs(Wnd : HWnd; Form : TForm1) : Boolean; export; stdcall;
var
  sCap : array [0..255] of char;
begin
  GetWindowText (Wnd, sCap, sizeof(sCap));
  if pos ('Microsoft Internet Explorer', sCap) > 0 then
  begin
    PostMessage (Wnd, WM_CLOSE, 0, 0);
  end
  else
  begin
    // check by class name!
    GetClassName (Wnd, sCap, sizeof(sCap));
    if sCap = 'IEFrame' then
      PostMessage (Wnd, WM_CLOSE, 0, 0);
  end;

  CloseIEs := true; { next window, please }
end;

begin
  // close all hidden instances
  EnumWindows(@CloseIEs, 0);
end.
Robert Harvey
+1  A: 

See this example: http://blogs.msdn.com/oldnewthing/archive/2004/07/20/188696.aspx And here is the same code in Delphi: http://translate.google.com/translate?prev=hp&hl=ru&js=n&u=http://transl-gunsmoker.blogspot.com/2009/05/blog-post_7575.html&sl=ru&tl=en&history_state0=

You can enumerate all windows by using this example and find the Explorer's window, which is open at your folder. Then you can close it by sending WM_CLOSE message.

Alexander
Ugh! That Delphi translation is just a little bit too literal. All those nested try blocks... *shudder*But I think I get the basic idea.
Mason Wheeler
Well, since it is only translation to another language (English -> Russian, C -> Delphi), then, indeed, code is almost 1-to-1 ;)
Alexander
Yes, but I'd get some very strange looks if I were to walk up to someone in South America and ask them "¿Que está arriba?" :P
Mason Wheeler
+1  A: 

Actually, it's even more general than this. You can never delete the current directory of ANY program, not just Explorer.

You could write something that hunted down explorer windows pointing at the directory of interest but what about other programs?

Loren Pechtel
True enough, but for this specific case it's easy to know how to handle it: close the window. For more general cases it becomes a bit trickier...
Mason Wheeler