Author: Jonas Bilinkevicius
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.
1
2 function TMainForm.WaitForWindowAndType(WindowCaption, TextToSend: string;
3 SecondsToWait: Cardinal): boolean;
4 var
5 h: Hwnd;
6 i: cardinal;
7 vk: word;
8 begin
9 i := SecondsToWait;
10 repeat
11 Application.ProcessMessages;
12 sleep(1000);
13 h := FindWindow(nil, pchar(WindowCaption));
14 dec(i);
15 until
16 (i < 1) or (h > 0);
17 result := not (h < 1);
18 if h < 1 then
19 begin
20 {do nothing}
21 end
22 else
23 begin
24 memo1.Lines.Add(format('Found %s, after %d seconds.', [WindowCaption,
25 SecondsToWait - i]));
26 sendmessage(h, WM_ACTIVATE, 0, 0);
27 sendmessage(h, WM_SETFOCUS, 0, 0);
28 i := 1;
29 while integer(i) <= length(TextToSend) do
30 begin
31 if texttosend[i] = '@' then
32 begin
33 inc(i);
34 vk := VkKeyScan(texttosend[i]);
35 keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), 0, 0); {this is the ALT key}
36 keybd_event(vk, MapVirtualKey(VK, 0), 0, 0); {ALT Letter}
37 keybd_event(vk, MapVirtualKey(VK, 0), KEYEVENTF_KEYUP, 0); {Letter UP}
38 keybd_event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0); {ALT
39 UP}
40 end
41 else
42 begin
43 vk := VkKeyScan(texttosend[i]);
44 if vk shr 8 = 1 then
45 begin
46 keybd_event(VK_SHIFT, 0, 0, 0);
47 keybd_event(vk, 0, 0, 0);
48 keybd_event(vk, 0, KEYEVENTF_KEYUP, 0);
49 keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
50 end
51 else
52 begin
53 keybd_event(vk, 0, 0, 0);
54 keybd_event(vk, 0, KEYEVENTF_KEYUP, 0);
55 end;
56 end;
57 sleep(100);
58 inc(i);
59 end;
60 end;
61 end;
|