如何最佳地向另一个应用程序的模态窗口添加项目?

6
什么是向另一个应用程序的模态窗口添加项目的最佳方法?
我为此编写了一个简单的示例(作为概念证明),使用了一种我认为对于微不足道的后台进程来说过于繁重的方法,但我很难想出替代方法。
例如,假设您是医生,正在填写处方数据的模态窗口。您输入了30天,并带有11个剂量重复,然后患者说他们要90天,并带有3个剂量重复。原始应用程序(您无法访问其源代码)没有易于转换的方法。我编写了一个小型实用程序,它通过定时器和findwindow监视特定的窗口,当找到它时,使自己可见并将自己放置在目标模态窗口的空白位置上。按下“30”按钮时,处方写入30天,带有11个剂量重复;按下“90”按钮时,则完成所需操作。如果模态窗口移动,则30和90按钮也会随之移动。虽然这可以正常工作,但我担心重复运行findwindow的定时器会带来太大的开销。
1)是否有更好的方法? 2)我对此感到担忧吗? 3)您是否因我的修补程序效率低下而暗自发笑?
提前感谢 - 我对这里的人们印象非常好!

4
我能想到的替代方法是安装一个全局的CBT钩子,这种方法容易出错且存在问题,并且在资源方面也不是免费的。如果你的轮询频率不是太快,那么定时器是个不错的选择。 - Sertac Akyuz
@Sertac:那么...您认为“过于频繁的轮询”是什么?我没有注意到系统性能的恶化或CPU的增加(这两个都是非常粗略的指标,我确信)在250ms的轮询间隔下,但这似乎“不对劲”…比那慢一点会导致按钮无法平滑地跟随表单。 - b-p
1
@b-p 你可以使用1秒的间隔来查找(轮询)窗口,当找到一个窗口时,切换到250毫秒以保持平滑。这样,即使没有目标窗口存在,也会对系统造成更少的负担。 - ain
1
我建议使用一个Shell钩子来监听Windows的激活。 - iamjoosy
@iamjoosy - 哪个shell钩子?我相信sertac关于CBT钩子的话,但不确定其他钩子中哪一个最好。我对使用钩子还很新。 - b-p
1个回答

1

最好的方法是... DLL注入。

// The DLL:
library dll_inj;

uses
  ShareMem,
  System.SysUtils,
  System.Classes, Vcl.Dialogs,
  windows, messages;

{$R *.res}

var
  hWndMain, hDemoButton, hEdit, hNewButton, hWndEnter: THandle;
  OldWndProc: TFarProc;
  hBtnFont: hFont;
  Times: integer;
  dwThreadId: DWORD;

function NewWndProc(hWnd: hWnd; Msg: UINT; wParam: wParam; lParam: lParam)
  : Longint; stdcall;
begin
  if Times = 0 then
  begin
    Times := Times + 1;
    hWndMain := FindWindowEx(0, 0, 'TForm1', 'Injection test');
    if hWndMain = 0 then
      OutputDebugString('hWndMain is 0!');

    hNewButton := CreateWindow('button', 'NewBtn', WS_CHILD or WS_VISIBLE, 20,
      20, 100, 24, hWndMain, 2000, GetWindowLong(hWndMain, GWL_HINSTANCE), nil);
    if hNewButton = 0 then
      OutputDebugString('CreateWindow failed!')
    else
    begin
      hWndEnter := FindWindowEx(hWndMain, 0, 'TBitBtn', 'Enter');
      if hWndEnter <> 0 then
        hBtnFont := SendMessage(hWndEnter, WM_GETFONT, 0, 0);
      if hBtnFont <> 0 then
        SendMessage(hNewButton, WM_SETFONT, hBtnFont, 1);
    end;

    hDemoButton := FindWindowEx(hWndMain, 0, 'TButton', 'Demo');
    if hDemoButton <> 0 then
    begin
      if not EnableWindow(hDemoButton, true) then
        OutputDebugString('EnableWindow failed!');
    end
    else
      OutputDebugString('hDemoButton is 0!');

    hEdit := FindWindowEx(hWndMain, 0, 'TEdit', 'Serial');
    if hEdit = 0 then
      OutputDebugString('hEdit is 0!')
    else if not SetWindowText(hEdit, 'You have been hacked') then
      OutputDebugString('SetWindowText failed!');
  end;

  case Msg of
    WM_COMMAND:
      if (hNewButton <> 0) and (DWORD(lParam) = hNewButton) then
        MessageBox(HWND_DESKTOP, 'You pressed a new button!', 'Yay!', MB_OK)
      else if (hWndEnter <> 0) and (DWORD(lParam) = hWndEnter) then
      begin
        MessageBox(HWND_DESKTOP, 'This message is not default anymore!',
          'Override!', MB_OK);
        Exit(0); // Suppress default event completely
      end;
  end;
  Result := CallWindowProc(OldWndProc, hWnd, Msg, wParam, lParam);
end;

procedure EntryPoint(Reason: integer);
begin
  hWndMain := FindWindowEx(0, 0, 'TForm1', 'Injection test');
  if hWndMain = 0 then
  begin
    OutputDebugString('hWndMain is 0!');
    Exit;
  end;

  OldWndProc := TFarProc(SetWindowLong(hWndMain, GWL_WNDPROC,
    LONG(@NewWndProc)));

  MessageBox(0, 'DLL Injected', 'OK', 0);
end;

begin
  CreateThread(nil, 0, @EntryPoint, nil, 0, &dwThreadId);

end.

// The injector:
program exe_inj2;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, windows, TLHelp32;

Function EnumThreadProc(wnd: HWND; Var appHwnd: HWND): LongBool; stdcall;
Var
  buf: array [0 .. 256] of Char;
Begin
  Result := LongBool(1);
  if GetClassname(wnd, buf, sizeof(buf)) > 0 then
    If StrComp(buf, 'TApplication') = 0 Then
    Begin
      appHwnd := wnd;
      Result := False;
    End;
End;

Function FindApplicationWindow(forThreadID: DWORD): HWND;
Begin
  Result := 0;
  EnumThreadWindows(forThreadID, @EnumThreadProc, lparam(@Result));
End;

Function ProcessIDFromAppname32(appname: String): DWORD;
{ Take only the application filename, not full path! }
Var
  snapshot: THandle;
  processEntry: TProcessEntry32;
Begin
  Result := 0;
  appname := UpperCase(appname);
  snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  If snapshot <> 0 Then
    try
      processEntry.dwSize := sizeof(processEntry);
      If Process32First(snapshot, processEntry) Then
        Repeat
          If Pos(appname,
            UpperCase(ExtractFilename(StrPas(processEntry.szExeFile)))) > 0 Then
          Begin
            Result := processEntry.th32ProcessID;
            Break;
          End; { If }
        Until not Process32Next(snapshot, processEntry);
    finally
      CloseHandle(snapshot);
    End; { try }
End;

function InjectDLL(dwPID: DWORD; DLLPath: PWideChar): integer;
var
  dwThreadID: Cardinal;
  hProc, hThread, hKernel: THandle;
  BytesToWrite, BytesWritten: SIZE_T;
  pRemoteBuffer, pLoadLibrary: Pointer;
begin
  if not FileExists(DLLPath) then
  begin
    MessageBox(0, PWideChar('File ' + DLLPath + ' does not exist'), 'Error', 0);
    Exit(0);
  end;

  hProc := OpenProcess(PROCESS_CREATE_THREAD or PROCESS_QUERY_INFORMATION or
    PROCESS_VM_OPERATION or PROCESS_VM_WRITE or PROCESS_VM_READ, False, dwPID);
  if hProc = 0 then
    Exit(0);
  try
    BytesToWrite := sizeof(WideChar) * (Length(DLLPath) + 1);
    pRemoteBuffer := VirtualAllocEx(hProc, nil, BytesToWrite, MEM_COMMIT,
      PAGE_READWRITE);
    if pRemoteBuffer = nil then
      Exit(0);
    try
      if not WriteProcessMemory(hProc, pRemoteBuffer, DLLPath, BytesToWrite,
        BytesWritten) then
        Exit(0);
      hKernel := GetModuleHandle('kernel32.dll');
      pLoadLibrary := GetProcAddress(hKernel, 'LoadLibraryW');
      hThread := CreateRemoteThread(hProc, nil, 0, pLoadLibrary, pRemoteBuffer,
        0, dwThreadID);
      try
        WaitForSingleObject(hThread, INFINITE);
      finally
        CloseHandle(hThread);
      end;
    finally
      VirtualFreeEx(hProc, pRemoteBuffer, 0, MEM_RELEASE);
    end;
  finally
    CloseHandle(hProc);
  end;
  Exit(1);
end;

const
  PROCESS_NAME = 'Default_project.exe';

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    WriteLn(PROCESS_NAME + ' PID: ' +
      IntToSTr(ProcessIDFromAppname32(PROCESS_NAME)));
    InjectDLL(ProcessIDFromAppname32(PROCESS_NAME), 'dll_inj.dll');
    ReadLn;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;

end.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接