Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to capture system wide key press

Posted on 2004-08-23
8
Medium Priority
?
245 Views
Last Modified: 2013-12-04
While my application is running, I like to get notified when the user presses the escape key.

Can some one give me example code how to setup a hook in a Console application using C or C++?
0
Comment
Question by:AUDRABRETT7
  • 4
  • 3
8 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 400 total points
ID: 11872291
Just see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwui/html/msdn_hooks32.asp ("Win32 Hooks"). It basically boils down to creating a DLL that is called by your console application, e.g.

#define __DLL

#ifndef _DEBUG
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

#ifdef _DEBUG
#include <crtdbg.h>
#endif

#pragma warning(disable:4786)   // 'identifier truncated to 255 characters'
#include "KeyHook.h"


#pragma data_seg( ".shared")
HHOOK       g_hhk   =   NULL;
#pragma data_seg()

HINSTANCE   g_hThisDll;

LRESULT CALLBACK    HookProc    (   int     nCode,  
                                    WPARAM  wParam,
                                    LPARAM  lParam  
                                );

int APIENTRY    DllMain (   HINSTANCE   hInstance,
                            DWORD       dwReason,
                            LPVOID      lpReserved
                        )
{
    if  (   dwReason    ==  DLL_PROCESS_ATTACH)
        {
#ifdef _DEBUG
            OutputDebugString   (   "KeyHook->DllMain(): DLL_PROCESS_ATTACH\n");
#endif

            g_hThisDll  =   hInstance;

            CreateLocalSwapMap  ();

            return  (   DisableThreadLibraryCalls   (   g_hThisDll));
        }

    if  (   dwReason    ==  DLL_PROCESS_DETACH)
        {
#ifdef _DEBUG
            OutputDebugString   (   "KeyHook->DllMain(): DLL_PROCESS_DETACH\n");
#endif
            DestroyLocalSwapMap ();
        }

    return( TRUE);
}

LRESULT CALLBACK HookProc   (   int     nCode,  // hook code
                                WPARAM  wParam, // removal flag
                                LPARAM  lParam  // address of structure with message
                            )
{
    PMSG    pmsg    =   ( PMSG) lParam;

    if  (   0   >   nCode   ||  PM_NOREMOVE ==  wParam)
        {
            return  (   CallNextHookEx  (   g_hhk,
                                            nCode,
                                            wParam,
                                            lParam
                                        )
                    );
        }

    if  (       WM_KEYDOWN  ==  pmsg->message
            ||  WM_KEYUP    ==  pmsg->message  
        )
        {
            /* this one is for us, so check key state */
#ifdef _DEBUG
            OutputDebugString   (   "KeyHook->HookProc():\tAction!\n");
#endif

            if  (   VK_ESC ==  pmsg->wParam )
            {
                // ESC was pressed, action!
            }
                       
        }

    return  (   CallNextHookEx  (   g_hhk,
                                    nCode,
                                    wParam,
                                    lParam
                                )
            );
}

LONG __DYNLINK KeyHookInit  ( void)
{
    HANDLE  hev;
#ifdef _DEBUG
    OutputDebugString   (   "KeyHook->KeyHookInit()\n");
#endif

    if  (   g_hhk)  return  (   ERROR_ALREADY_EXISTS);

    g_hhk   =   SetWindowsHookEx    (   WH_GETMESSAGE,
                                        ( HOOKPROC) HookProc,
                                        g_hThisDll,
                                        0
                                    );
#ifdef _DEBUG
    _ASSERT (   g_hhk);
#endif

    if  (   !(  hev =   CreateEvent (   NULL,  
                                        FALSE,  
                                        FALSE,  
                                        KeyHook_EVENT_NAME
                                    )
            )
        )
        {
            if  (   ERROR_ALREADY_EXISTS    ==  GetLastError    ())
                {
                    if  (   !(  hev =   OpenEvent   (   EVENT_ALL_ACCESS,  
                                                        FALSE,  
                                                        KeyHook_EVENT_NAME
                                                    )
                            )
                        )
                        {
#ifdef _DEBUG
                            OutputDebugString   (   "KeyHook:\tERROR opening event\n");
#endif
                            return  (   -1);
                        }
                }
             else  
                {
#ifdef _DEBUG
                    OutputDebugString   (   "KeyHook:\tERROR creating event\n");
#endif
                    return  (   -2);
                }
        }

    WaitForSingleObject (   hev,    INFINITE);

    Sleep   (   5000);

    return  (   0);
}

LONG __DYNLINK KeyHookTerm  ( void)
{
    HANDLE  hev;

#ifdef _DEBUG
    OutputDebugString   (   "KeyHook->KeyHookTerm()\n");
#endif

    UnhookWindowsHookEx (   g_hhk);

//  g_hhk   =   NULL;

    Sleep   (   5000);

    if  (   !(  hev =   OpenEvent   (   EVENT_ALL_ACCESS,  
                                        FALSE,  
                                        KeyHook_EVENT_NAME
                                    )
            )
        )
        {  
#ifdef _DEBUG
            OutputDebugString   (   "KeyHook->UnHook():\tERROR opening event!\n");
#endif
            return  (   GetLastError    ());
        }

    PulseEvent  (   hev);

    return  (   0);
}
0
 

Author Comment

by:AUDRABRETT7
ID: 11873579
How can I do this without using an additional DLL?

I want my program to be stand alone.


How can I do the hook from my executable itself?
0
 
LVL 86

Expert Comment

by:jkr
ID: 11873640
>> How can I do this without using an additional DLL?

No way. System-wide hooks require using a separate DLL, since this DLL will be mapped into every process' address space. Check the article.
0
Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 

Author Comment

by:AUDRABRETT7
ID: 11873739
Then can I do a hook to a DOS application that is running in a "normal window"?

And can I do this hook without using an additional DLL?

If so, can you provide example?
0
 
LVL 86

Expert Comment

by:jkr
ID: 11874048
You mean you want to hook *only* the console application? BTW, console apps do not process windows messages, so this approach will not work.
0
 

Author Comment

by:AUDRABRETT7
ID: 11887252
>You mean you want to hook *only* the console application? BTW, console apps do not process
>>windows messages, so this approach will not work.

OK, lets say for testing purposes that it's another windows application.
How can I hok it then?
0
 

Author Comment

by:AUDRABRETT7
ID: 11896286
jkr,
How can I hook a single windows application?
0
 
LVL 2

Accepted Solution

by:
carribus earned 1600 total points
ID: 11901504
Hi AUDRA...

Here are the conditions and rules when it comes down to hooking in windows:

1. Your application wishes to install a hook for itself:
    - Your hook procedure can reside in the application (single file solution)

2. You wish to have a means of hooking other applications:
    - Your hook will need to reside inside a dll.

Those are the hard and fast rules. However, you can get creative in a number of ways:

1. You can contain the .dll inside the .exe file as a resource, and extract it to the drive each time your .exe file executes, then link it dynamically and then create the hook. However, this kind of thing is way beyond the scope of this question. So the original points 1 and 2 apply.
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

If you have ever found yourself doing a repetitive action with the mouse and keyboard, and if you have even a little programming experience, there is a good chance that you can use a text editor to whip together a sort of macro to automate the proce…
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…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …

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