MFC, Determine if \'this\' app has focus


/ Published in: C++
Save to your folder(s)

Determine if 'this' app has focus.
Using MFC.


Copy this code and paste it in your HTML
  1. static HWND hWnd2 = (HWND)-1;
  2. HWND hWnd = ::GetForegroundWindow();
  3.  
  4. if ( hWnd2==hWnd )
  5. {
  6. return;
  7. }
  8.  
  9. hWnd2 = hWnd;
  10.  
  11. int slength = ::GetWindowTextLength(hWnd) + 1; // length of its title bar text
  12. CString wintext;
  13. ::GetWindowText(hWnd, wintext.GetBufferSetLength(slength), slength); // get title bar text
  14. wintext.ReleaseBuffer();
  15.  
  16. DWORD dwProcessIdFocus;
  17. // Use Windows API GetWindowThreadProcessId to find the window's process ID.
  18. GetWindowThreadProcessId( hWnd, &dwProcessIdFocus );
  19.  
  20. // Use Windows API GetCurrentProcessId to find 'this' process ID.
  21. DWORD dwProcessIdParent = GetCurrentProcessId();
  22.  
  23. bool thisAppHasFocus = dwProcessIdFocus==dwProcessIdParent;
  24.  
  25. CString msg;
  26. msg.Format(
  27. "%s%s
  28. "
  29. "HWND: 0x%X
  30. "
  31. "Process ID: %d",
  32. wintext.GetLength() ? wintext : "(null)",
  33. thisAppHasFocus ? " (me)" : "",
  34. hWnd,
  35. dwProcessIdFocus
  36. );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.