Thursday, September 10, 2009

Find Window by partial title?

If you ever played with FindWindow function you should know that it defined in Windows.pas unit as
 function FindWindow(lpClassName, lpWindowName: PChar): HWND;

lpClassName window's class name
lpWindowName caption(text) of the window
Function can be used to find for instance Notepad as
...
var
 wHandle: Handle{Cardinal, DWORD, HWND};
begin
 wHandle := FindWindow(nil, 'Untitled - Notepad');
end;

Well it's simple, right? Yes it's simple if the caption does not change, but if it does then it's not 'Untitled - Notepad' but 'MyDocumentName.txt - Notepad', but I can see a pattern here, can you? The text ' - Notepad' doesn't change, oh yeah! We can now retrieve the window handle with this function which I've used in my previous post "Mass e-mail sender" to retrieve Opera's window handle. The function is declared as
function FindWindowExtd(partialTitle: string): HWND;
var
  hWndTemp: hWnd;
  iLenText: Integer;
  cTitletemp: array [0..254] of Char;
  sTitleTemp: string;
begin
  hWndTemp := FindWindow(nil, nil);
  while hWndTemp <> 0 do begin
    iLenText := GetWindowText(hWndTemp, cTitletemp, 255);
    sTitleTemp := cTitletemp;
    sTitleTemp := UpperCase(copy( sTitleTemp, 1, iLenText));
    partialTitle := UpperCase(partialTitle);
    if pos( partialTitle, sTitleTemp ) <> 0 then
      Break;
    hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
  end;
  result := hWndTemp;
end;

Now we can use this function to get Notepad's window handle regardless of it's caption as
...
var
 hNotepad: Hwnd;
begin
 hNotepad := FindWindowExt(' - Notepad');
end;

It's simply SEE: Simple, Efficient, Easy!

6 comments:

  1. how to use this ?

    ReplyDelete
  2. Amazing! Thanks a lot!

    ReplyDelete
  3. Nice! dude how get setparent using handle firefox are client? example, my form delphi inside firefox.. help me please!

    ReplyDelete
  4. OK, Now how do we extract the actual Title of Notepad window so we could, for example, close notepad using the following command...

    sendmessage(findwindow(nil,'Untitled - Notepad'),wm_close,1,1);

    ReplyDelete
  5. @Anonymous
    the usage example:
    var
    hNotepad: Hwnd;
    begin
    hNotepad := FindWindowExt(' - Notepad');
    end;

    helps you grab the window Handle, therefore your FindWindow is unnecessary, you could easily do
    var
    hNotepad: Hwnd;
    begin
    hNotepad := FindWindowExt(' - Notepad');
    sendmessage(hNotepad, WM_Close, 1, 1);
    end;

    ReplyDelete

Blogroll(General programming and Delphi feeds)