ExternalWindowTracker.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. #include "stdafx.h"
  2. #include "externalwindowtracker.h"
  3. #include "Misc.h"
  4. #include "SendKeys.h"
  5. #include "Options.h"
  6. #include "CP_Main.h"
  7. #include "UAC_Helper.h"
  8. ExternalWindowTracker::ExternalWindowTracker(void)
  9. {
  10. m_activeWnd = NULL;
  11. m_focusWnd = NULL;
  12. m_dittoHasFocus = false;
  13. m_desktopHasFocus = false;
  14. m_AccessibleObjectFromWindow = NULL;
  15. m_hOleacc = LoadLibrary(_T("oleacc.dll"));
  16. if (m_hOleacc)
  17. {
  18. m_AccessibleObjectFromWindow = (AccessibleObjectFromWindow)GetProcAddress(m_hOleacc, "AccessibleObjectFromWindow");
  19. }
  20. }
  21. ExternalWindowTracker::~ExternalWindowTracker(void)
  22. {
  23. if (m_hOleacc)
  24. {
  25. FreeLibrary(m_hOleacc);
  26. m_hOleacc = NULL;
  27. m_AccessibleObjectFromWindow = NULL;
  28. }
  29. }
  30. bool ExternalWindowTracker::TrackActiveWnd(bool force)
  31. {
  32. if(force == false && IdleSeconds() < (CGetSetOptions::GetMinIdleTimeBeforeTrackFocus() / 1000.0))
  33. {
  34. Log(StrF(_T("Not Idle for long enough, IdleTime: %f, MinIdle %f"), IdleSeconds(), (CGetSetOptions::GetMinIdleTimeBeforeTrackFocus() / 1000.0)));
  35. return false;
  36. }
  37. m_desktopHasFocus = false;
  38. BOOL fromHook = true;
  39. HWND newFocus = NULL;
  40. HWND newActive = ::GetForegroundWindow();
  41. if(CGetSetOptions::GetUseGuiThreadInfoForFocus())
  42. {
  43. GUITHREADINFO guiThreadInfo;
  44. guiThreadInfo.cbSize = sizeof(GUITHREADINFO);
  45. DWORD OtherThreadID = GetWindowThreadProcessId(newActive, NULL);
  46. if(GetGUIThreadInfo(OtherThreadID, &guiThreadInfo))
  47. {
  48. newFocus = guiThreadInfo.hwndFocus;
  49. }
  50. }
  51. else
  52. {
  53. if(AttachThreadInput(GetWindowThreadProcessId(newActive, NULL), GetCurrentThreadId(), TRUE))
  54. {
  55. newFocus = GetFocus();
  56. AttachThreadInput(GetWindowThreadProcessId(newActive, NULL), GetCurrentThreadId(), FALSE);
  57. }
  58. }
  59. if(newFocus == 0 && newActive != 0)
  60. {
  61. newFocus = newActive;
  62. }
  63. else if(newActive == 0 && newFocus != 0)
  64. {
  65. newActive = newFocus;
  66. }
  67. if(newFocus == 0 || !IsWindow(newFocus) || newActive == 0 || !IsWindow(newActive))
  68. {
  69. Log(_T("TargetActiveWindow values invalid"));
  70. return false;
  71. }
  72. if(NotifyTrayhWnd(newActive) || NotifyTrayhWnd(newFocus))
  73. {
  74. Log(_T("TargetActiveWindow shell tray icon has active"));
  75. return false;
  76. }
  77. if(IsAppWnd(newFocus) || IsAppWnd(newActive))
  78. {
  79. if(m_dittoHasFocus == false)
  80. {
  81. Log(StrF(_T("Ditto has focus - Active: %s (%d), Focus: %s (%d), FromHook %d"), WndName(m_activeWnd), m_activeWnd, WndName(m_focusWnd), m_focusWnd, fromHook));
  82. }
  83. m_dittoHasFocus = true;
  84. return false;
  85. }
  86. TCHAR cName[MAX_PATH];
  87. GetClassName(newActive, cName, _countof(cName));
  88. CString className(cName);
  89. if (className == _T("Progman"))
  90. {
  91. m_desktopHasFocus = true;
  92. }
  93. m_focusWnd = newFocus;
  94. m_activeWnd = newActive;
  95. m_dittoHasFocus = false;
  96. if(theApp.QPasteWnd())
  97. theApp.QPasteWnd()->UpdateStatus(true);
  98. Log(StrF(_T("TargetActiveWindow Active: %s (%d), Focus: %s (%d), FromHook %d, IdleTime: %f"), WndName(m_activeWnd), m_activeWnd, WndName(m_focusWnd), m_focusWnd, fromHook, IdleSeconds()));
  99. return true;
  100. }
  101. bool ExternalWindowTracker::WaitForActiveWnd(HWND activeWnd, int timeout)
  102. {
  103. DWORD start = GetTickCount();
  104. while(((int)(GetTickCount() - start)) < timeout)
  105. {
  106. if(::GetForegroundWindow() == activeWnd)
  107. {
  108. Log(StrF(_T("found focus wait %d"), GetTickCount()-start));
  109. return true;
  110. }
  111. Sleep(0);
  112. ActivateTarget();
  113. }
  114. Log(_T("Didn't find focus"));
  115. return false;
  116. }
  117. void ExternalWindowTracker::ActivateFocus(const HWND activeHwnd, const HWND focushWnd)
  118. {
  119. CString csApp = GetProcessName(m_activeWnd);
  120. Log(StrF(_T("SetFocus - AppName: %s, Active: %d, Focus: %d"), csApp, m_activeWnd, m_focusWnd));
  121. if (focushWnd != NULL)
  122. {
  123. AttachThreadInput(GetWindowThreadProcessId(activeHwnd, NULL), GetCurrentThreadId(), TRUE);
  124. if (GetFocus() != focushWnd)
  125. {
  126. SetFocus(focushWnd);
  127. }
  128. AttachThreadInput(GetWindowThreadProcessId(activeHwnd, NULL), GetCurrentThreadId(), FALSE);
  129. }
  130. }
  131. bool ExternalWindowTracker::NotifyTrayhWnd(HWND hWnd)
  132. {
  133. HWND hParent = hWnd;
  134. int nCount = 0;
  135. while(hParent != NULL)
  136. {
  137. TCHAR className[100];
  138. GetClassName(hParent, className, (sizeof(className) / sizeof(TCHAR)));
  139. if((STRCMP(className, _T("Shell_TrayWnd")) == 0) ||
  140. (STRCMP(className, _T("NotifyIconOverflowWindow")) == 0) ||
  141. (STRCMP(className, _T("TrayNotifyWnd")) == 0))
  142. {
  143. return true;
  144. }
  145. hParent = ::GetParent(hParent);
  146. if(hParent == NULL)
  147. break;
  148. nCount++;
  149. if(nCount > 100)
  150. {
  151. Log(_T("GetTargetName reached maximum search depth of 100"));
  152. break;
  153. }
  154. }
  155. return false;
  156. }
  157. bool ExternalWindowTracker::ActivateTarget()
  158. {
  159. Log(StrF(_T("Activate Target - Active: %d, Focus: %d"), m_activeWnd, m_focusWnd));
  160. if (IsIconic(m_activeWnd))
  161. {
  162. ShowWindow(m_activeWnd, SW_RESTORE);
  163. }
  164. // Save specified timeout period...
  165. PVOID timeoutMS = 0;
  166. SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &timeoutMS, 0);
  167. // ... then set it to zero to disable it
  168. SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)0, 0);
  169. //If we are doing this and we are not the current foreground window then attach to the current bef
  170. //setting the focus window
  171. //this shouldn't happen that much, most of the time we are the foreground window
  172. bool detach = false;
  173. DWORD foreGroundProcessId = GetWindowThreadProcessId(::GetForegroundWindow(), NULL);
  174. if(foreGroundProcessId != GetCurrentThreadId())
  175. {
  176. Log(_T("Attach to process, calling set foreground from non forground window"));
  177. if(AttachThreadInput(foreGroundProcessId, GetCurrentThreadId(), TRUE))
  178. {
  179. detach = true;
  180. }
  181. }
  182. BringWindowToTop(m_activeWnd);
  183. SetForegroundWindow(m_activeWnd);
  184. if(detach)
  185. {
  186. AttachThreadInput(foreGroundProcessId, GetCurrentThreadId(), FALSE);
  187. }
  188. //check to see if this app should set focus
  189. //this is off by default
  190. CString csApp = GetProcessName(m_activeWnd);
  191. if(CGetSetOptions::GetSetFocusToApp(csApp))
  192. {
  193. ActivateFocus(m_activeWnd, m_focusWnd);
  194. }
  195. SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)timeoutMS, 0);
  196. //Sleep(250);
  197. return true;
  198. }
  199. void ExternalWindowTracker::SendPaste(bool activateTarget)
  200. {
  201. HWND activeWnd = m_activeWnd;
  202. CSendKeys send;
  203. send.AllKeysUp();
  204. if(activateTarget)
  205. {
  206. DWORD startTick = GetTickCount();
  207. ActivateTarget();
  208. theApp.PumpMessageEx();
  209. WaitForActiveWnd(activeWnd, max(25, CGetSetOptions::WaitForActiveWndTimeout()));
  210. DWORD endTick = GetTickCount();
  211. if((endTick-startTick) > 150)
  212. Log(StrF(_T("Paste Timing Send Paste around activate Target: %d"), endTick-startTick));
  213. }
  214. else
  215. {
  216. activeWnd = ::GetForegroundWindow();
  217. }
  218. CString csPasteToApp = GetProcessName(activeWnd);
  219. CString csPasteString = CGetSetOptions::GetPasteString(csPasteToApp);
  220. DWORD delay = CGetSetOptions::SendKeysDelay();
  221. DWORD sendKeysDelay = CGetSetOptions::RealSendKeysDelay();
  222. m_dittoHasFocus = false;
  223. Log(StrF(_T("Sending paste to app %s key stroke: %s, SeDelay: %d"), csPasteToApp, csPasteString, delay));
  224. bool pasteAsAdmin = false;
  225. if (CGetSetOptions::GetPasteAsAdmin())
  226. {
  227. pasteAsAdmin = CUAC_Helper::PasteAsAdmin(activeWnd);
  228. }
  229. //can't run an elevated app when running windows app
  230. if(CGetSetOptions::GetIsWindowsApp() == FALSE &&
  231. pasteAsAdmin &&
  232. theApp.UACThreadRunning() == false)
  233. {
  234. Log(StrF(_T("Passing paste off to uac aware app")));
  235. if (theApp.UACPaste() == false)
  236. {
  237. pasteAsAdmin = false;
  238. }
  239. }
  240. if (pasteAsAdmin == false)
  241. {
  242. if(activateTarget)
  243. {
  244. Sleep(delay);
  245. }
  246. send.SetKeyDownDelay(sendKeysDelay);
  247. send.SendKeys(csPasteString, true);
  248. }
  249. Log(_T("Post sending paste"));
  250. }
  251. void ExternalWindowTracker::SendCopy(CopyReasonEnum::CopyReason copyReason)
  252. {
  253. CSendKeys send;
  254. send.AllKeysUp();
  255. HWND activeWnd = GetForegroundWindow();
  256. CString csToApp = GetProcessName(activeWnd);
  257. CString csString = CGetSetOptions::GetCopyString(csToApp);
  258. DWORD delay = CGetSetOptions::SendKeysDelay();
  259. DWORD SendKeysDelay = CGetSetOptions::RealSendKeysDelay();
  260. Sleep(delay);
  261. theApp.PumpMessageEx();
  262. Log(StrF(_T("Sending copy to app %s key stroke: %s, Delay: %d"), csToApp, csString, delay));
  263. bool pasteAsAdmin = false;
  264. if (CGetSetOptions::GetPasteAsAdmin())
  265. {
  266. pasteAsAdmin = CUAC_Helper::PasteAsAdmin(activeWnd);
  267. }
  268. //can't run an elevated app when running windows app
  269. if(CGetSetOptions::GetIsWindowsApp() == FALSE &&
  270. pasteAsAdmin &&
  271. theApp.UACThreadRunning() == false)
  272. {
  273. Log(StrF(_T("Passing copy off to uac aware app")));
  274. if (theApp.UACCopy() == false)
  275. {
  276. pasteAsAdmin = false;
  277. }
  278. }
  279. if (pasteAsAdmin == false)
  280. {
  281. //give the app some time to take focus before sending paste
  282. Sleep(delay);
  283. send.SetKeyDownDelay(SendKeysDelay);
  284. theApp.SetCopyReason(copyReason);
  285. send.SendKeys(csString, true);
  286. }
  287. Log(_T("Post sending copy"));
  288. }
  289. // sends Ctrl-X to the TargetWnd
  290. void ExternalWindowTracker::SendCut()
  291. {
  292. CSendKeys send;
  293. send.AllKeysUp();
  294. CString csToApp = GetProcessName(m_activeWnd);
  295. CString csString = CGetSetOptions::GetCutString(csToApp);
  296. DWORD delay = CGetSetOptions::SendKeysDelay();
  297. DWORD sendKeysDelay = CGetSetOptions::RealSendKeysDelay();
  298. Sleep(delay);
  299. theApp.PumpMessageEx();
  300. Log(StrF(_T("Sending cut to app %s key stroke: %s, Delay: %d"), csToApp, csString, delay));
  301. bool pasteAsAdmin = false;
  302. if (CGetSetOptions::GetPasteAsAdmin())
  303. {
  304. pasteAsAdmin = CUAC_Helper::PasteAsAdmin(m_activeWnd);
  305. }
  306. //can't run an elevated app when running windows app
  307. if(CGetSetOptions::GetIsWindowsApp() == FALSE &&
  308. pasteAsAdmin &&
  309. theApp.UACThreadRunning() == false)
  310. {
  311. Log(StrF(_T("Passing copy off to uac aware app")));
  312. if (theApp.UACCut() == false)
  313. {
  314. pasteAsAdmin = false;
  315. }
  316. }
  317. if (pasteAsAdmin == false)
  318. {
  319. //give the app some time to take focus before sending paste
  320. Sleep(delay);
  321. send.SetKeyDownDelay(sendKeysDelay);
  322. send.SendKeys(csString, true);
  323. }
  324. Log(_T("Post sending cut"));
  325. }
  326. CString ExternalWindowTracker::ActiveWndName()
  327. {
  328. return WndName(m_activeWnd);
  329. }
  330. CString ExternalWindowTracker::WndName(HWND hWnd)
  331. {
  332. TCHAR cWindowText[200];
  333. HWND hParent = hWnd;
  334. ::GetWindowText(hParent, cWindowText, 100);
  335. int nCount = 0;
  336. while(STRLEN(cWindowText) <= 0)
  337. {
  338. hParent = ::GetParent(hParent);
  339. if(hParent == NULL)
  340. break;
  341. ::GetWindowText(hParent, cWindowText, 100);
  342. nCount++;
  343. if(nCount > 100)
  344. {
  345. Log(_T("GetTargetName reached maximum search depth of 100"));
  346. break;
  347. }
  348. }
  349. return cWindowText;
  350. }
  351. bool ExternalWindowTracker::ReleaseFocus()
  352. {
  353. if( IsAppWnd(::GetForegroundWindow()) )
  354. {
  355. return ActivateTarget();
  356. }
  357. return false;
  358. }
  359. CPoint ExternalWindowTracker::FocusCaret()
  360. {
  361. CPoint pt(-1, -1);
  362. if(!m_activeWnd || !m_focusWnd)
  363. return pt;
  364. //first try getting the caret position using IAccessible object
  365. if (m_AccessibleObjectFromWindow)
  366. {
  367. {
  368. IAccessible* pIAccessible = NULL;
  369. HRESULT hr = m_AccessibleObjectFromWindow(m_activeWnd, OBJID_CARET, __uuidof(IAccessible), (void**)&pIAccessible);
  370. if (hr == S_OK)
  371. {
  372. long left = 0, top = 0, width = 0, height = 0;
  373. VARIANT varCaret;
  374. varCaret.vt = VT_I4;
  375. varCaret.lVal = CHILDID_SELF;
  376. hr = pIAccessible->accLocation(&left, &top, &width, &height, varCaret);
  377. pIAccessible->Release();
  378. if (hr == S_OK && left != 0 && top != 0)
  379. {
  380. // calculate offset of caret by Accessible
  381. pt.SetPoint(left + width, top + 20);
  382. }
  383. }
  384. }
  385. }
  386. if (pt.x != -1 && pt.y != -1)
  387. return pt;
  388. //next try GetGUIThreadInfo
  389. GUITHREADINFO guiThreadInfo;
  390. guiThreadInfo.cbSize = sizeof(GUITHREADINFO);
  391. DWORD OtherThreadID = GetWindowThreadProcessId(m_activeWnd, NULL);
  392. if(GetGUIThreadInfo(OtherThreadID, &guiThreadInfo))
  393. {
  394. CRect rc(guiThreadInfo.rcCaret);
  395. if(rc.IsRectEmpty() == FALSE)
  396. {
  397. pt = rc.BottomRight();
  398. ::ClientToScreen(m_focusWnd, &pt);
  399. }
  400. }
  401. if(pt.x != -1 && pt.y != -1)
  402. return pt;
  403. //last try attatching to there thread
  404. DWORD currentThreadId = GetCurrentThreadId();
  405. if(AttachThreadInput(OtherThreadID, currentThreadId, TRUE))
  406. {
  407. BOOL ok = GetCaretPos(&pt);
  408. if(ok && (pt.x != 0 && pt.y != 0))
  409. {
  410. ::ClientToScreen(m_focusWnd, &pt);
  411. if (pt.y != 0 && pt.x != 0)
  412. {
  413. // calculate offset of caret by GetCaretPos
  414. pt.y += 20;
  415. }
  416. else
  417. {
  418. pt.x = -1;
  419. pt.y = -1;
  420. }
  421. }
  422. else
  423. {
  424. pt.x = -1;
  425. pt.y = -1;
  426. }
  427. AttachThreadInput(OtherThreadID, currentThreadId, FALSE);
  428. }
  429. return pt;
  430. }