Search code examples
windowsdelphiwindow-handles

Creating a function to dig for Windows Handle by Classname(s) Only


So I just got an answer to my question about getting the Skype Chatbox handle.

I am now trying to create a simple function, that digs for a handle. Here is how I am hoping to be able to use it:

MyHWND := DigForHandle(['Notepad','Edit'],['Untitled - Notepad','']);

Params:

1) Array of String: Holds the Class Hierachy.

2) Array of String: Holds the Window Caption Hierachy.

As you see, the 2nd entry in the 2nd parameter is empty, since the Edit Class does not have a Window Caption.

Would it be possible to create such function? :)


Solution

  • When I thought about it, I realized that it was actually rather simple - the code I had though, was "confusing" for me, which was why I asked a question here. After trying it out, I found that doing it this way, its a lot easier to read, and not as complicated (IMO).

    Function DigForHandle(ClassHierachy, TextHierachy : Array of String):HWND;
    Var
     Handle : HWND;
     I : Integer;
     PClass,PText : PChar;
    
    Begin
    
     Result := 0;
    
     I := 0;
     while (I <= Length(ClassHierachy)-1) do
     begin
       PClass := PChar(ClassHierachy[I]);
       PText  := PChar(TextHierachy[I]);
    
       if PClass = '' then PClass := Nil;
       if PText = '' then PText := Nil;
    
    
       Result := FindWindowEx(Result,0,PClass,PText);
    
       Inc(I);
     end;
    
    
    
    End;