简体   繁体   中英

Retrieving keyboard state in C# using DirectInput?

I need to retrieve the keyboard state when a key is pressed on a particular form rather quickly - fast enough that the standard KeyUp/KeyDown events for windows forms are not fast enough. I was told to try out DirectInput, but I have no experience working with the library or any threading experience, so I am unsure of how to start at all.

How would I set up a thread which called a function on the form back each time DirectInput picks up changes in keyboard state? I know how to initialize the device and that SetEventNotification is pretty much what I want, but I do not know how to use it.

Any help would be greatly appreciated!

The solution probably depends on what you mean when you say that the key-up/key-down events for windows aren't fast enough. They certainly work at sub-millisecond resolution - which is massively faster than most peoples fingers - so what benefit do you hope to achieve by reading the input 'faster'?

Are you sure it's not just that your event loop or code is slowing down the response?

You can achieve similar (identical?) speeds to DirectInput's polling of the keyboard state using the windows functions GetAsyncKeyState/GetKeyState. I haven't used the latest version of DirectInput but I'm pretty sure that earlier versions just used the same Win32 events for non-polled keyboard state. DirectInput's main advantage is that it provides common abstractions over all kinds of input devices - it's not really for 'fast' keyboard input (whatever that means).

You can see on Microsoft's own documentation that ' The use of DirectInput for keyboard and mouse input is not recommended... '

This may help you as in not having to use DirectInput:

[DllImport("user32.dll")]
private static 
extern short GetAsyncKeyState(System.Int32 vKey);

http://msdn.microsoft.com/en-us/library/ms646293(v=vs.85).aspx

hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM