开发者

How do I respond to a specific sequence of key presses?

The end result is very simple, I have to have something happen when a user types in the letter "n" "o" "t" "e" in that order. 'Note' is the word.

I'm making a little application for a friend 开发者_StackOverflowthat will help him take notes, and I want my application to become visible when he types in "note" from anywhere on the machine.

Here's what I've got so far:

if (e.KeyCode == neededLetter as Keys)
            {
                neededLetter = "o";
            }

I initialize the neededLetter variable with "N" but I'm stuck there. Any help?


The easiest way I've found to handle global keyboard hooks is to just write a script with AutoHotKey. You can compile the scripts to a tray applications so users don't need to install AutoHotKey.

Here's a rough example of what you're asking for. I didn't test it, but it should capture any time "note" is typed, activate notepad if it's running, or start notepad if it isn't running...

:*:note::
    IfWinExist, ahk_class Notepad
        WinActivate, ahk_class Notepad
    else
        Run, Notepad
return


First, to do it from anywhere on the machine you'll need to either hook all keyboard input or find some other way of catching the letters as they come in. I'm not sure how that's done in C#, but it should be possible.

For the actual typing, you'll want something like (this isn't perfect, necessarily):

if (e.KeyCode == neededLetter as Keys)
{
    if ( neededLetter == "n" )
    {
        neededLetter = "o";
    } else if ( neededLetter == "o" ) {
        neededLetter = "t";
    } else if ( neededLetter == "t" ) {
        neededLetter = "e";
    } else if ( neededLetter == "e" ) {
        // you now have the full sequence typed, show your app
    }
} else { // not sure if this is valid, but it's the idea
    neededLetter = "n"; // reset the sequence if another letter is typed
}


you might also want to consider matching "non-word characters" (like whitespace or punctuation) before the "n" or after the "e".

Otherwise, your app would recognize other words like nanotechnology, and that might be annoying for the user.


Try something like this:

These are class level declarations

string keySequence = "Note";
int nextKey = 0;

Now in event handler:

if (e.KeyCode != keySequence[nextKey++] as Keys)
{
    nextKey = 0;
}
if(nextKey == keySequence.Length)
{
    // The sequence successfully matched here, do what you want
}


  1. look for N
  2. is next letter O? If no, reset back to N
  3. is next letter T? If no, reset back to N
  4. is next letter E? If no, reset back to N
  5. show app.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜