title: Windows Global Hook C++
body: <p>I've been reading posts all over and trying different approaches, but I can't make this work.</p>
  
  <p>I want to be able to track the last window before the user clicks on my application. This way I can bring it to the front and send a copy command to retrieve whatever the user has selected.</p>
  
  <p>I thought about using hooks to receive notifications of activated windows, but it is not working as expected. I'm using <strong>HSHELL_WINDOWACTIVATED</strong> global hook to keep track of the current and last active window, but I always get both handles to be the same, pointing to my application.</p>
  
  <p>The code looks like:</p>
  
  <pre><code>#pragma data_seg("ASEG")  
    HWND lastWindow = 0;
    HWND currentWindow = 0;
  #pragma data_seg()  
  #pragma comment(linker, "/section:ASEG,RWS") 
  
  HINSTANCE dllHandle;  
  
  BOOL APIENTRY DllMain(    
           HINSTANCE hinstDLL,  
           DWORD fdwReason,  
           PVOID lpReserved )  
  { 
      switch( fdwReason )  
      {  
      case DLL_PROCESS_ATTACH:    
          dllHandle = hinstDLL;    
          return TRUE;  
          break;  
      }  
  }  
  
  LRESULT CALLBACK ShellHookProc(int nCode, WPARAM wParam, LPARAM lParam)   
  {  
      if (nCode &gt; 0)
      {
          switch (nCode)
          {
          case HSHELL_WINDOWACTIVATED: lastWindow = currentWindow;
                           currentWindow = (HWND)wParam;
                           break;
          }
      }
  
      return ::CallNextHookEx(NULL, nCode,wParam,lParam);
  }
  
  extern "C" {
  
  __declspec(dllexport) void Init()
  {   
      SetWindowsHookEx(WH_SHELL, ShellHookProc, dllHandle, 0);    
  }
  
  }
  </code></pre>
  
  <p>Later on I would use the lastWindow to bring that window to the front and send a Ctrl+C command.</p>
  
  <p>If you call GetWindowTextA(..) for each handle, the first time you activate a different window and go back to the application, lastWindow retrieves blank and currentWindow my application name. Any consecutive activations retrieve always the name of my application for both lastWindow and currentWindow. 
  I don't quite understand why this is happening. Any ideas?</p>
  
  <p>Thanks!</p>