2004. március 5., péntek

How to find a window by its (partial) title and close it


Problem/Question/Abstract:

How can I close an unwanted popup window using its partial title? I have tried destroywindow, however, it cannot close the window I want to close.

Answer:

Well, first you need to get a handle to the window. The following code can find a window by window title (even a partial title, and is case insensisitive) .

function HWndGet(partialTitle: string): hWnd;
var
  hWndTemp: hWnd;
  iLenText: Integer;
  cTitletemp: array[0..254] of Char;
  sTitleTemp: string;
begin
  hWndTemp := FindWindow(nil, nil);
  {Find first window and loop through all subsequent windows in the master window list}
  while hWndTemp <> 0 do
  begin
    {Retrieve caption text from current window}
    iLenText := GetWindowText(hWndTemp, cTitletemp, 255);
    sTitleTemp := cTitletemp;
    sTitleTemp := UpperCase(copy(sTitleTemp, 1, iLenText));
    {Clean up the return string, preparing for case insensitive comparison.
                Use appropriate method to determine if the current window's caption either
          starts with or contains passed string}
    partialTitle := UpperCase(partialTitle);
    if pos(partialTitle, sTitleTemp) <> 0 then
      break;
    {Get next window in master window list and continue}
    hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
  end;
  result := hWndTemp;
end;

Once you have the handle you then send the window a WM_CLOSE or WM_QUIT message.
For example:

var
  theHandle: THandle;
begin
  theHandle := HWndGet('Apps Title');
  if theHandle <> 0 then
    SendMessage(theHandle, WM_CLOSE, 0, 0);
  { or SendMessage(theHandle, WM_QUIT, 0, 0); }
end;

1 megjegyzés: