[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

How to capture system wide key press

Posted on 2004-08-23
8
Medium Priority
?
244 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 

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

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
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…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

649 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