delphi - 如何通过鼠标单击将另一个应用程序的窗口句柄传递给 Delphi

标签 delphi winapi mouse delphi-xe

如何通过用户通过单击鼠标选择窗口(可以是任何其他应用程序的窗口)来获取要传递给 Delphi 的窗口句柄。在我的 Delphi 应用程序中,我可以有一个用户单击的按钮来启动此检测过程,以及一个在 Delphi 应用程序中显示单击的窗口标题的标签。当用户满意他选择了正确的窗口时,他可以单击我的 Delphi 应用程序(这将是模态的)中的按钮来停止选择过程,并让我的应用程序开始对另一个窗口执行它需要执行的操作...

最佳答案

如果您知道窗口标题中的文本是什么,此代码将为您解决问题:

var
  WindowList: TList;

function GetHandle (windowtitle: string): HWND;
var
  h, TopWindow: HWND;
  Dest: array[0..80] of char;
  i: integer;
  s: string;

  function getWindows(Handle: HWND; Info: Pointer): BOOL; stdcall;
    begin
      Result:= True;
      WindowList.Add(Pointer(Handle));
    end;

begin
  result:= 0;

  try
    WindowList:= TList.Create;
    TopWindow:= Application.Handle;
    EnumWindows(@getWindows, Longint(@TopWindow));
    i:= 0;
    while (i < WindowList.Count) and (result = 0) do
      begin
        GetWindowText(HWND(WindowList[i]), Dest, sizeof(Dest) - 1);
        s:= dest;
        if length(s) > 0 then
          begin
            if (Pos(UpperCase(Windowtitle), UpperCase(s)) >= 1) then
              begin
                h:= HWND(WindowList[i]);
                if IsWindow(h) then
                  result:= h
             end
           end;
        inc(i)
      end
    finally
      WindowList.Free;
    end;
end;

示例中的用法(记事本将打开的文件的名称放在窗口标题中):

h:= getHandle('text.txt');
if (h = 0)
  // Oops not found
else 
  begin
    // you got the handle!
  end;

我使用此代码来检查我的应用程序是否已启动并运行。但它可以在任何启动的应用程序上使用。

关于delphi - 如何通过鼠标单击将另一个应用程序的窗口句柄传递给 Delphi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5608502/

相关文章:

python - 如何在Python中的给定窗口中捕获鼠标移动?

Delphi 2009 处理 with

Delphi:文件访问和兼容性文件(Windows 7)

c++ - ChangeServiceConfig2 使用GetProcAddress 支持多版本windows

delphi - 无法使用默认程序打开位图文件

java - OpenGL 鼠标输入

delphi - 使用 TControlBar,如何将 strip 的移动限制为单行?

delphi - OpenCV Haar 级联 xml 格式

winapi - 如何在 Windows 文件对话框的 "save"按钮上设置文本?

vim - 通过腻子在 Vim 中选择多页文本 block 时向上/向下滚动