function FindWindowThroughWindowText(WindowText: string): THandle; var hCurrentWindow: THandle; cnt: Integer; WindowTitle: array[0..254] of Char; begin Result := INVALID_HANDLE_VALUE; //返回值预设为无效的句柄 hCurrentWindow := GetForegroundWindow; //找出当前操作系统中活动的第一个窗口 cnt := 1; //计数器置初值=1 while True do begin if GetWindowText(hCurrentWindow, @WindowTitle, 255) > 0 then //如果找到窗口的标题 if StrPos(WindowTitle, PChar(WindowText)) <> nil then //如果找到的正是目标窗口则 break; //跳出循环 hCurrentWindow := GetWindow(hCurrentWindow, GW_HWNDNEXT); //找下一窗口
//直到找到或超过一定的次数后退出 if hCurrentWindow = 0 then begin //如果顺序查一遍后未找到目标窗口,则重新从头开始查找, hCurrentWindow := GetWindow(Application.Handle, GW_HWNDFIRST); //找到第一个窗口 inc(cnt); // 循环计数器加1 if cnt > 10000 then begin //如果超出10000次则(在此10000次循环过程中等待windows建立完//目标窗口,如在此过程中找到则成功退出,否则10000次后(约30秒至1分钟)仍未找到,提示用户是否继续查找) if MessageDlg('找不到运行中的' + WindowText + '窗口,可能该系统已损坏!是否继续运行?', mtConfirmation, [mbOK, mbCancel], 0) = mrOK then begin //请用户选择是否继续查找//如用户选择继续查找,则 cnt := 1; //循环计数器重置初值=1 Continue; //开始新一轮查找 end else exit; //如用户放弃查找,则退出 end; end; end; Result := hCurrentWindow; //返回值为找到的窗口句柄 end;