title: Simple hooking procedure
body: <p>I'm trying to make a simple globalhook that prints some text into a .txt file whenever someone presses a key on the keyboard. The problem is that when I execute my program and press on a key in a certain program, the program gets stuck and doesn't respond anymore. So I think the problem is that the hookprocedure doesn't work/return properly when called.</p>
  
  <p>this is the code in my .exe file:</p>
  
  <pre><code>#include &lt;Windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;wingdi.h&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  typedef bool (*install)();
  install instal;
  HINSTANCE hinst;
  
  int main()
  {
  hinst = LoadLibrary(TEXT("injectdll.dll"));
  if(!hinst)
  {
  printf("The DLL could not be found.\n");
  }
  
  instal = (install) GetProcAddress(hinst, "install");
  if(!instal) 
  {
      printf("The function was not found.\n");
  }
  
  if(!instal())
  {
      printf("func couldn't be executed");
  }
  
  printf("Program successfully hooked.\nPress enter to unhook the function and stop the program.\n");
  getchar();
  }
  </code></pre>
  
  <p>this is the code in my dll:</p>
  
  <pre><code>    #include &lt;windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  #include &lt;Strsafe.h&gt;
  
  using namespace std;
  
  #pragma data_seg(".shared")
  HHOOK hook = 0;
  #pragma data_seg()
  #pragma comment(linker, "/SECTION:.shared,RWS")
  
  HINSTANCE hinst;
  
  LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) 
  {
  if (code &lt; 0) 
  {
      return CallNextHookEx(hook, code, wParam, lParam);
  }
  FILE *file;
  fopen_s(&amp;file, "function.txt", "a+");
  fprintf(file, "Function keyboard_hook called.\n");
  fclose(file);
  
  return 0;
  }
  
  extern "C" __declspec(dllexport) bool install() 
  { 
  hook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC) meconnect, hinst, 0);
  return hook != NULL;
  }
  
  BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD Reason, LPVOID Reserved) {
  
  switch(Reason) {
  case DLL_PROCESS_ATTACH:
              hinst = hDLL;
      break;
  case DLL_PROCESS_DETACH:
      break;
  case DLL_THREAD_ATTACH:
      break;
  case DLL_THREAD_DETACH:
      break;
  }
  
  return TRUE;
  }
  </code></pre>
  
  <p>the meconnect function returns 0, I don't know if this is right, but I also tried returning: 
  return CallNextHookEx(hook, code, wParam, lParam);
  and
  return CallNextHookEx(0, code, wParam, lParam);</p>
  
  <p>both didn't change anything in the results.</p>