1
0

grabwnd.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include ".\grabwnd.h"
  2. #include <strsafe.h>
  3. #define LCID_INVARIANT MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT)
  4. typedef struct _GRABDATA
  5. {
  6. HHOOK hook;
  7. HWND hwndParent;
  8. WCHAR szClassName[256];
  9. WCHAR szTitle[256];
  10. GRABCB callback;
  11. ULONG_PTR user;
  12. } GRABDATA;
  13. static GRABDATA g_grab = {0, 0, };
  14. static BOOL IsTargetClass(HWND hwnd, LPCWSTR plzClassName)
  15. {
  16. wchar_t szName[256] = {0};
  17. return (0x00 == plzClassName[0] ||
  18. (GetClassNameW(hwnd, szName, sizeof(szName)/sizeof(wchar_t)) &&
  19. CSTR_EQUAL == CompareStringW(LCID_INVARIANT, NORM_IGNORECASE, szName, -1, plzClassName, -1)));
  20. }
  21. static BOOL IsTargetTitle(HWND hwnd, LPCWSTR pszTitle)
  22. {
  23. wchar_t szName[256] = {0};
  24. return (0x00 == pszTitle[0] ||
  25. (GetWindowTextW(hwnd, szName, sizeof(szName)/sizeof(wchar_t)) &&
  26. CSTR_EQUAL == CompareStringW(LCID_INVARIANT, NORM_IGNORECASE, szName, -1, pszTitle, -1)));
  27. }
  28. static LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam)
  29. {
  30. if (HCBT_CREATEWND == code && IsTargetClass((HWND)wParam, g_grab.szClassName) &&
  31. IsTargetTitle((HWND)wParam, g_grab.szTitle) &&
  32. (!g_grab.hwndParent || ((CBT_CREATEWND*)lParam)->lpcs->hwndParent == g_grab.hwndParent))
  33. {
  34. LRESULT result;
  35. if (g_grab.callback)
  36. {
  37. g_grab.callback((HWND)wParam, ((CBT_CREATEWND*)lParam)->lpcs, &((CBT_CREATEWND*)lParam)->hwndInsertAfter, g_grab.user);
  38. }
  39. result = CallNextHookEx(g_grab.hook, code, wParam, lParam);
  40. UnhookWindowsHookEx(g_grab.hook);
  41. ZeroMemory(&g_grab, sizeof(GRABDATA));
  42. return result;
  43. }
  44. return CallNextHookEx(g_grab.hook, code, wParam, lParam);
  45. }
  46. BOOL BeginGrabCreateWindow(LPCWSTR pszClassName, LPCWSTR pszTitle, HWND hwndParent, GRABCB callback, ULONG_PTR user)
  47. {
  48. if (g_grab.hook || !callback) return FALSE;
  49. if (pszClassName) StringCchCopyW(g_grab.szClassName, sizeof(g_grab.szClassName)/sizeof(wchar_t), pszClassName);
  50. else g_grab.szClassName[0] = 0x00;
  51. if (pszTitle) StringCchCopyW(g_grab.szTitle, sizeof(g_grab.szTitle)/sizeof(wchar_t), pszTitle);
  52. else g_grab.szTitle[0] = 0x00;
  53. g_grab.hwndParent = hwndParent;
  54. g_grab.callback = callback;
  55. g_grab.user = user;
  56. g_grab.hook = SetWindowsHookEx(WH_CBT, HookProc, NULL, GetCurrentThreadId());
  57. if (!g_grab.hook) ZeroMemory(&g_grab, sizeof(GRABDATA));
  58. return (NULL != g_grab.hook);
  59. }
  60. void EndGrabCreateWindow(void)
  61. {
  62. if (g_grab.hook) UnhookWindowsHookEx(g_grab.hook);
  63. ZeroMemory(&g_grab, sizeof(GRABDATA));
  64. }