Sebastian
Sebastian

Reputation: 1263

Windows Global Hook C++

I've been reading posts all over and trying different approaches, but I can't make this work.

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.

I thought about using hooks to receive notifications of activated windows, but it is not working as expected. I'm using HSHELL_WINDOWACTIVATED 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.

The code looks like:

#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 > 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);    
}

}

Later on I would use the lastWindow to bring that window to the front and send a Ctrl+C command.

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?

Thanks!

Upvotes: 0

Views: 4239

Answers (1)

Ryan Griggs
Ryan Griggs

Reputation: 2748

I think you can use SetWinEventHook. This hook should allow you to capture the EVENT_SYSTEM_FOREGROUND message so that each time a window is brought to the foreground, you can capture the window handle. Then when your app window is activated, just look at the last value you captured.

See this: https://stackoverflow.com/a/4407715/1502289

Also, in your own code, you could simply do a comparison to see if the window handle is the handle to your own window. If not, save the handle.

Example:

...
case HSHELL_WINDOWACTIVATED: 
if (lastWindow != [your own window's handle])
{
    lastWindow = (HWND)wParam;
}
break;
...

Upvotes: 1

Related Questions