Author: Jonas Bilinkevicius
I am trying to build a component to get info about the programs executing in my NT4
environment. I managed to get the names for all the windows running (title text).
Now, how can I get the process ID for each of them? Which function should I use? Is
there any function that tells me for how long my process is running?
Answer:
It is better to use the EnumWindows function instead of FindWindow/GetWindow,
because the latter isn't sensitive to windows being destroyed halfway through the
loop and you can end up getting invalid handles. Here's an example:
1 2 function EnumWindowsProc(hWnd: LongWord; Form: TForm1): WordBool; stdcall;
3 begin4 Form.FoundAWindow(hWnd);
5 Result := True
6 end;
7 8 procedure TForm1.FoundAWindow(hWnd: LongWord);
9 var10 ProcessID: LongWord;
11 Title: array[0..255] of Char;
12 begin13 GetWindowThreadProcessID(hWnd, @ProcessID);
14 GetWindowText(hWnd, Title, 256);
15 {Now, do whatever you want with Title and ProcessID, e.g.:}16 Memo1.Lines.Add(Title + ' [' + IntToStr(ProcessID) + ']')
17 end;
18 19 procedure TForm1.Timer1Timer(Sender: TObject);
20 begin21 EnumWindows(@EnumWindowsProc, Integer(Self))
22 end;