Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Wait for keyboard input text sequence via C#

Status
Not open for further replies.

answers123

Technical User
May 2, 2008
33
US
Hi there,

I want to know is it possible via a keyboard hook in C# to monitor all input for a certain text sequence, e.g. WN0P, and then do what I need once the text has been input via the keyboard?

If so, how do I do that, I only have found articles on checking for a specific key.

Thanks
 
Not a very elegant solution - and it needs some serious thought and refactoring, but this should get you started. Note: I just used a WPF handler in this example.

Code:
        readonly string magicCombination = "WNOP";
        string keystrokes = string.Empty;

        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
        { 
            //refactor this (regex for character?)
            if (e.Key == Key.Space  || e.Key == Key.Tab || e.Key == Key.Enter) //etc. etc.
            {
                //reset keystroke tracking
                ResetKeyStrokes();
                UpdateUI(string.Empty);
                return;
            }
            keystrokes += e.Key.ToString();
            UpdateUI(keystrokes);

            if (keystrokes.EndsWith(magicCombination))
            {
                //call method to do whatever the magic combo is supposed to trigger here
                //I am just updating a textblock
                ResetKeyStrokes();
                UpdateUI("Magic Combination!");
                return;
            }
        }

        private void UpdateUI(string incomingText)
        {
            txtbxKeyStrokes.Text = incomingText;
        }

        private void ResetKeyStrokes()
        {
            keystrokes = string.Empty;
        }

good luck!

-Mark
 
Thanks for that Mark. Unfortunately I seem to be missing something as when I put that into a Windows Form and run it and start typing it never hits the OnPreviewKeyDown function? I need to be able to monitor all keyboard entries, not just in the C# application, I'm trying to implement what I need via C#, if you follow what I mean?
 
I attached the OnPreviewDown method on the eventhandler "PreviewKeyDown" of the WPF window. In the case of Windows Forms, I would attach it to the form.

If you want something outside of a running application, it looks like you may want something else (Windows Service?). Unfortunately, I'm not sure what, exactly. Sorry I couldn't be more help.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top