[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

system wide hook

Posted on 1998-12-30
8
Medium Priority
?
760 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 80 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
Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

 
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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

This article shows how to make a Windows 7 gadget that accepts files dropped from the Windows Explorer.  It also illustrates how to give your gadget a non-rectangular shape and how to add some nifty visual effects to text displayed in a your gadget.…
As more and more people are shifting to the latest .Net frameworks, the windows presentation framework is gaining importance by the day. Many people are now turning to WPF controls to provide a rich user experience. I have been using WPF controls fo…
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…
Loops Section Overview

830 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