Thursday, May 5, 2011

Capturing keystrokes

If I am working in an application and I press key from keyboard, how can I capture that key (or string), including the source application's name, using C#?

From stackoverflow
  • You could override the ProcessCmdKey function of the control you want to capture the input from.

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        var msgFormat = "Key Pressed: [{0}] {1}";
        var appName = System.AppDomain.CurrentDomain.FriendlyName;
        var logMsg = String.Format(msgFormat, appName, keyData.ToString());
        // write msg to log
        return base.ProcessCmdKey(ref msg, keyData);
    }
    

    Hope that helps.

  • There is a good keylogger example on codeproject.com. I hope this helps.

  • You need to setup windows hooks to call your callback function for any keyboard event. You can use SetWindowsHookEx to set up windows hooks.

    Check this article on MSDN blog to read more about it.

    http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.