Solved

system wide hook

Posted on 1998-12-30
8
718 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
 
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Visual Fox Pro commands 15 29
Mixed results 10 69
Windows 10 Scheduled Tasks 11 63
Windows Process running 3 40
This article shows how to make a Windows 7 gadget that extends its U/I with a flyout panel -- a window that pops out next to the gadget.  The example gadget shows several additional techniques:  How to automatically resize a gadget or flyout panel t…
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
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…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

759 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now