How to record keys pressed?
Essentially I want to record every key press (including keydown/keyup and mouse clicks) and when they occurred so开发者_JAVA百科 that I can create a macro out of them.
I found a ton of stuff about key presses and WinForms or WPF, but I don't really need a GUI, I just want to dump it out to the console after I'm done processing it.
So how can I record all key presses, even when my console window doesn't have focus?
Sample output:
Send {q down}
Sleep 98
Send {q up}
Sleep 4
Send {f down}
Sleep 102
Send {f up}
Sleep 43
Send {a down}
Sleep 26
Send {s down}
Sleep 111
Send {a up}
Sleep 18
Send {s up}
Sleep 17
Send {a down}
Sleep 62
Send {space down}
Sleep 72
Send {a up}
Sleep 5
Send {space up}
Using WPF for now, but the input text field has to be focused. I'd rather be able to record the keystrokes while I'm in my game, hence the question :)
Have a look at the SetWindowsHookEx function. This can be used to monitor keystrokes across the system.
As far as I know, in order to accomplish this you will need to hook into Win32 API.
This project may help you get started.
Just a suggestion, you should take a close look at keyboard low level hooks, they (for the most part) work between consoles and winforms. This might be of some help as well: http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx
try this
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx
(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
I too was looking for this- found this link which provides a class which does it all :)
http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx
You can use HwndSource.FromHwnd method to return an HwndSource for
a window where HwndSource represents WPFcontent within a Win32 window
Then AddHook method is used to add a callback method named CallBackMethod,
which will receive all messages for the window. For this, the following code has been used:
HwndSource windowSpecificOSMessageListener = HwndSource.FromHwnd(new
WindowInteropHelper(this).Handle);
windowSpecificOSMessageListener.AddHook(new HwndSourceHook(CallBackMethod));
In the Callback Method, all the OS messages of this window specific is received.
private IntPtr CallBackMethod(IntPtr hwnd,
int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// msg can be WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101 and so forth.
// Add you code
}
精彩评论