Solved

system wide hook

Posted on 1998-12-30
8
728 Views
Last Modified: 2013-12-03
Here is my source code of my sample hook program. But, it does not work, can anyone help me?

Application:

#include <windows.h>
#include <string.h>
#include <stdio.h>
 

__declspec(dllimport) LRESULT CALLBACK ShellProc(int code, WPARAM wParam, LPARAM lParam);
__declspec(dllimport) BOOL Hook(void);
__declspec(dllimport) BOOL Unhook(void);

LRESULT CALLBACK WindowFunc(HWND, UINT, WPARAM, LPARAM);

char szWinName[] = "MyWin";


int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst,
                           LPSTR lpszArgs, int nWinMode)
{
      MSG msg;
      WNDCLASSEX wcl;
    HWND hwnd;

    Hook();
      wcl.hInstance = hThisInst;
      wcl.lpszClassName = szWinName;
      wcl.lpfnWndProc = WindowFunc;
      wcl.style = 0;
      wcl.cbSize = sizeof(WNDCLASSEX);
      wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
      wcl.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
      wcl.hCursor = LoadCursor(NULL, IDC_ARROW);
      wcl.lpszMenuName = NULL;
      wcl.cbClsExtra = 0;
      wcl.cbWndExtra = 0;
      wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);

      if(!RegisterClassEx(&wcl))
            return 0;

      hwnd = CreateWindow(szWinName, "Sample", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
                            CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP,
                                    NULL,hThisInst, NULL);
 
   
        
    ShowWindow(hwnd, nWinMode);
      UpdateWindow(hwnd);


      while(GetMessage(&msg, NULL, 0, 0))
      {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            
      }
      Unhook();
      return msg.wParam;
}

LRESULT CALLBACK WindowFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
            
      switch(message)
      {
          case WM_CREATE:
               break;
      
          case WM_DESTROY:
                  PostQuitMessage(0);
            break;

          default:
            return DefWindowProc(hwnd,message, wParam, lParam);
      }
      return 0;
}

DLL:

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>

__declspec(dllexport) LRESULT CALLBACK ShellProc(int code, WPARAM wParam, LPARAM lParam);



////////////////////////////////////////////////////////////////////////////////
// Shared variables (must be initialized)

#pragma comment(linker, "-section:.shared,rws")
#pragma data_seg(".shared")

HHOOK g_hHook = NULL;    

#pragma data_seg()
////////////////////////////////////////////////////////////////////////////////
// Global variables

HINSTANCE g_hinstDll = NULL; // Current DLL instance handle
FILE *LogFil;

////////////////////////////////////////////////////////////////////////////////

// DLL initialization and termination routine

BOOL APIENTRY DllMain(HINSTANCE hinstDll, DWORD reason, LPVOID reserved)
{
    UNREFERENCED_PARAMETER(reserved);
     
      switch(reason)
      {
      case DLL_PROCESS_ATTACH:
   
        DisableThreadLibraryCalls(hinstDll);
        g_hinstDll = hinstDll;  // Save DLL instance handle
        break;
    }
     
    return TRUE; // Success
}

////////////////////////////////////////////////////////////////////////////////

// Set the hook

__declspec(dllexport) BOOL Hook(void)
{
    // Is a hook allready in place
    if (g_hHook != NULL)
        return FALSE;
         
    LogFil = fopen("c:\\temp\\sample.txt","a+");
    g_hHook = SetWindowsHookEx(WH_SHELL, (HOOKPROC)ShellProc, g_hinstDll, 0);
    return (g_hHook != NULL);
     
}

////////////////////////////////////////////////////////////////////////////////
// Remove the hook

__declspec(dllexport) BOOL Unhook(void)
{
    BOOL rc;

    fclose(LogFil);
    rc = UnhookWindowsHookEx(g_hHook);
    if (rc)
        g_hHook = NULL;
     
    return rc;
}

////////////////////////////////////////////////////////////////////////////////
// The hook procedure

HRESULT CALLBACK ShellProc(int code, WPARAM wParam, LPARAM lParam)
{
   
   FILE *LogFil;

   if(code < 0)
      return CallNextHookEx(g_hHook, code, wParam, lParam);
   else if (code == HSHELL_WINDOWCREATED)
      {
     HWND WndHnd = (HWND)wParam;
     int Len =  GetWindowText(WndHnd, NULL,0) + 1;
     char *Ttl = new char[Len];
     GetWindowText(WndHnd,Ttl,Len);
     fwrite(Ttl,1,Len-1,LogFil);
     
   }
    return 0;
}




 
0
Comment
Question by:huaan
  • 5
  • 3
8 Comments
 
LVL 11

Accepted Solution

by:
alexo earned 20 total points
ID: 1417917
>> fwrite(Ttl,1,Len-1,LogFil);
First, do not use C library functions inside a global hook.  Use windows APIs instead (CreateFile(), WriteFile() and friends).

Second, you have two variables named LogFil, one in global scope and one in local scope.  Remove both of them and put the file handle (remember, windows APIs instead of C functions) in the *shared* section.

0
 
LVL 11

Expert Comment

by:alexo
ID: 1417918
BTW, the code looks vaguely familar...  ;-)
0
 

Author Comment

by:huaan
ID: 1417919
Thank you. It is worked now. But, l change the WH_SHELL into WH_CBT and HSHELL_WINDOWCREATED into HCBT_CREATEWND, the program is not working anymore. Can you give me some suggestions?
0
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
LVL 11

Expert Comment

by:alexo
ID: 1417920
An HCBT_CREATEWND notification is sent before the window is created while an HSHELL_WINDOWCREATED notification is sent after it was created.
0
 

Author Comment

by:huaan
ID: 1417921
After changing, my program can not run any more. Do you have any example?
0
 
LVL 11

Expert Comment

by:alexo
ID: 1417922
I usually work with WH_GETMESSAGE hooks.  Most flexible.
0
 

Author Comment

by:huaan
ID: 1417923
can you show me an example?
Thank you.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1417924
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a technique for converting RTF (Rich Text Format) data to HTML and provides C++ source that does it all in just a few lines of code. Although RTF is coming to be considered a "legacy" format, it is still in common use... po…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question