How to find a window by its (partial) title and close it (2) (Views: 29)
Problem/Question/Abstract: I am trying to figure out how I can get the handle of the main window of another application so I can terminate that program. I simply need to terminate one application from another application. Answer: This Code waits x seconds for a certain window to appear, tries to put it on top and send keystrokes to it. Pay special attention to the FindWindow Command. The Caption is the "EXACT" text in the window title bar. To do a partial match you have to have Windows ENUMERATE all it's open windows, then test the list that comes back. function TMainForm.WaitForWindowAndType(WindowCaption, TextToSend: string; SecondsToWait: Cardinal): boolean; var h: Hwnd; i: cardinal; vk: word; begin i := SecondsToWait; repeat Application.ProcessMessages; sleep(1000); h := FindWindow(nil, pchar(WindowCaption)); dec(i); until (i < 1) or (h > 0); result := not (h < 1); if h < 1 then begin {do nothing} end else begin memo1.Lines.Add(format('Found %s, after %d seconds.', [WindowCaption, SecondsToWait - i])); sendmessage(h, WM_ACTIVATE, 0, 0); sendmessage(h, WM_SETFOCUS, 0, 0); i := 1; while integer(i) <= length(TextToSend) do begin if texttosend[i] = '@' then begin inc(i); vk := VkKeyScan(texttosend[i]); keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), 0, 0); {this is the ALT key} keybd_event(vk, MapVirtualKey(VK, 0), 0, 0); {ALT Letter} keybd_event(vk, MapVirtualKey(VK, 0), KEYEVENTF_KEYUP, 0); {Letter UP} keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0); {ALT UP} end else begin vk := VkKeyScan(texttosend[i]); if vk shr 8 = 1 then begin keybd_event(VK_SHIFT, 0, 0, 0); keybd_event(vk, 0, 0, 0); keybd_event(vk, 0, KEYEVENTF_KEYUP, 0); keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0); end else begin keybd_event(vk, 0, 0, 0); keybd_event(vk, 0, KEYEVENTF_KEYUP, 0); end; end; sleep(100); inc(i); end; end; end; |