We help IT Professionals succeed at work.

open windows

kevinward66
kevinward66 asked
on
can someone give me code that will get all the open windows and their HANDLE into a Listview with 2 columns one called APPLICATION and the other HANDLE, and how can i click on a window in the listview and then click on a button to close it?


PLEASE help A.S.A.P
Comment
Watch Question

Simple example:

function EnumWindowsProc(Hw: hWnd; TF: TfrmEnumWin): Boolean; stdCall;
var
  WinName: array[0..144] of char;
  ListItem: TListItem;
begin
  Result:=True;
  { get the current window text }
  GetWindowText(Hw, WinName, 144);
  { get the class name }
  GetClassName(Hw, CName, 144);
  { now add to list view }
  ListItem := Form1.ListView1.Add;
  ListItem.Caption := WinName;
  ListItem.SubItems.Add(Format('$.8x', [Hw]));
end;

// button to refresh the window list
procedure Form1.ButtonRefreshClick(Sender: TObject);
begin
  ListView1.Clear;
  EnumWindows(@EnumWindowsProc, 0);
end;

// button to close
procedure Form1.ButtonCloseAppClick(Sender: TObject);
begin
  if ListView1.Selected = nil then
  begin
    MessageDlg('Please select an application to terminate',
      mtError, [mbOk], 0);
    ListView1.SetFocus;
    Exit;
  end;

  SendMessage(StrToInt(ListView1.Selected.SubItems[0]),
    WM_CLOSE, 0, 0);
end;



That's it :)
Hope it helps!

DragonSlayer.


PS: Some more stubborn applications require a TerminateProcess to terminate, though.

Commented:
DragonSlayer's code is almost correct, just 2 little hints:

(1) The result type of EnumWindowsProc should be "bool" (which is longbool = 4 byte boolean), not "boolean" (1 byte boolean). But this doesn't really make much of a difference, since both 1 and 4 byte booleans are returned in the 4 byte assembler eax register, anyway. But for the sake of cleanness...   :-)
(2) SendMessage with WM_CLOSE does not work reliably!! Please always use PostMessage for WM_CLOSE, that works *much* better. Using PostMessage the message goes other ways. With PostMessage it's like the user has clicked the [x] button, using SendMessage is different, so a lot of programs simply ignore it.

Regards, Madshi.
Thanks Madshi! :)

Commented:
You're welcome...   (-:

Author

Commented:
i cannot seem to get this code to work, its full of compile errors!!
oops

change
function EnumWindowsProc(Hw: hWnd; TF: TfrmEnumWin): Boolean; stdCall;

to

function EnumWindowsProc(Hw: hWnd; Param: LPARAM): Boolean; stdCall;


I'm also assuming that:
1. your form is called Form1
2. you have 2 buttons, one called ButtonRefresh, and the other, ButtonCloseApp
3. your listview is called ListView1

Author

Commented:
undeclared identifier

"CName"

can you help?
Oops again :)

Just remove the line that says
GetClassName(Hw, CName, 144);

Author

Commented:
ok, will try that!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.