日期:2014-05-19  浏览次数:21038 次

c# 监控键盘
问题:在我做的c#程序中监控其他软件的键盘输入然后写入数据库。

      在delphi中可以用钩子实现,不知道在c#中应该怎么实现,哪位csdn大佬,知道怎么做。     我先在这里谢过了~!        

        Thank   you   ~!!!!

        最好可以给个代码参考一下~!


------解决方案--------------------
在.NET中并不支持Hook,尤其是全局的Hook,如果确实要这么做,那么可以把Hook的代码编写到一个非托管的DLL中,比如用VC++编写的MFC或Win32Dll,在.NET的类库DLL中不好使的.
------解决方案--------------------
Why Global System Hooks and C# Don 't Play Well Together

Global system hooks have always been a problem for .NET developers. To understand why, we first need to discuss how hooks work at a system level and how Windows processes these event notifications.

Normally, an application implements hooks by creating a callback function and informing Windows of this function. When Windows processes a hookable event, such as mouse movement or the creation of a window, it calls this callback function, which the hooking application handles accordingly. With local hooks (when an application hooks other events taking place in the same process), this callback function can be located anywhere, and local hooks can be written pretty easily in C# -- a quick look around CodeProject reveals several examples. Unfortunately, Windows is not so permissive with global system hooks, which allow one process to intercept events from another process. Windows insists that the callback functions for global system hooks be located in DLLs. Neither C# nor VB.NET are able to produce standard Windows DLLs, which means they 're also unable to process global system hooks -- the MSDN library even explicitly says global system hooks cannot be handled within managed code applications. How discouraging!

Luckily, C# programmers are a clever and crafty bunch. Michael Kennedy, in his CodeProject article "Global System Hooks in .NET ", came up with a workaround. Using C++, he created a DLL that essentially worked as a wrapper to managed code. The C++ DLL registered a callback function with Windows. When a hook notification arrived in that callback, it called a managed code function. Using this technique, he was able to trap several hook notifications, such as low-level keyboard and mouse events. The problem he discovered, though, was that Windows changes the execution context when sending out certain hook notifications. When Windows hooked a low-level mouse or keyboard event, it called any hooking application from within the context of the hooking application. But for most other events, the callback function was called from the context of the hooked application. This essentially meant that his wrapper functions couldn 't be used with most Windows hooks.

来自于CODEPROJECT

------解决方案--------------------
vs2003 vs2005都行
我在n个项目中用了-_-#