Thursday, September 10, 2009

Click a window's button?

Now this function is awesome I needed some time ago for a special program which clicks on "Unblock" button on "Windows Security Alert" window :)
Here's the code
function EnumChildProc(Wnd: hWnd; SL: TStrings): BOOL; stdcall;
var
  szFull: array[0..MAX_PATH] of Char;
begin
  Result := Wnd <> 0;
  if Result then begin
    GetWindowText(Wnd, szFull, SizeOf(szFull));
    if (Pos(SL[0], StrPas(szFull)) > 0) and
       (SL.IndexOfObject(TObject(Wnd)) < 0) then
      SL.AddObject(StrPas(szFull), TObject(Wnd));
    EnumChildWindows(Wnd, @EnumChildProc, Longint(SL));
  end;
end;

function WindowBtnClick(ParentWindow: Hwnd; ButtonCaption: string): Boolean;
var
  SL: TStringList;
  H:  hWnd;
begin
  SL := TStringList.Create;
  try
    SL.AddObject(ButtonCaption, nil);
    EnumChildWindows(ParentWindow, @EnumChildProc, Longint(SL));
    H := 0;
    case SL.Count of
      1: Exit;
      2: H := hWnd(SL.Objects[1]);
      else
        Exit;
    end;
  finally
    SL.Free;
  end;
  Result := H <> 0;
  if Result then
    PostMessage(H, BM_CLICK, 0, 0);
end;

Usage
procedure TForm1.Button1Click(Sender: TObject);
var
  hCalculator: HWND;
label
  tryAgain;
begin
  tryAgain:
    hCalculator := FindWindow(nil, 'Calculator');
    if hCalculator <> 0 then
      WindowBTNclick(hCalculator, '2') else begin
        WinExec('calc', SW_SHOW);
        Sleep(1500);
        goto tryAgain;
    end;
end;

You can change '2' with anyother key, i.e. '9', apparently '1' is not working, I don't know why... anyways have fun!

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)