1

如果我在 C++ 中有一些表单应用程序,我将如何设置一些东西以便它监视特定的键序列以执行某些操作?例如,观察用户按特定顺序点击箭头键,然后打开另一个表单?

(显然这是.net?我是新手,所以我在这里有点迷路。)

4

1 回答 1

0

只要您可以要求 mainForm有焦点,一个简单的版本涉及将KeyPreview属性设置为true并添加处理程序PreviewKeyDown

#using <System::Windows::Forms.dll>

// for brevity of example
using namespace System;
using namespace System::Windows::Forms;

public ref class Form1 : Form
{
private:
    // desired key sequence
    static array<Keys>^ contra = { Keys::Up, Keys::Up, Keys::Down, Keys::Down,
                                   Keys::Left, Keys::Right, Keys::Left, Keys::Right,
                                   Keys::B, Keys::A, Keys::LaunchApplication1};

    // how far into the sequence the user currently is
    int keySeqPos;

    // some other data
    int lives;

    void Form1_PreviewKeyDown(Object^ sender, PreviewKeyDownEventArgs^ e)
    {
        if{keySeqPos < 0 || keySeqPos >= contra->Length)
        {
            // reset position if it's invalid
            keySeqPos = 0;
        }

        // use the following test if you don't care about modifiers (CTRL, ALT, SHIFT)
        // otherwise you can test direct equality: e->KeyCode == contra[keySeqPos]
        // caps lock, num lock, and scroll lock are harder to deal with
        if(e->KeyCode & Keys.KeyCode == contra[keySeqPos])
        {
            keySeqPos++
        }
        else
        {
            keySeqPos = 0;
            // alternatively, you could keep a history and check to see if a
            // suffix of it matches a prefix of your code, setting keySeqPos to
            // the length of the match
        }

        if(keySeqPos == contra->Length)
        {
            // key sequence complete, do whatever it is you want to do
            lives += 3;
        }
    }

    void InitializeComponent()
    {
        // other initialization code

        this->KeyPreview = true;
        this->PreviewKeyDown += gcnew PreviewKeyDownEventHandler(this, &Form1::Form1_PreviewKeyDown);
    }

public:

    Form1()
    {
        InitializeComponent();

        keySeqPos = 0;
        lives = 3;
    }
}
于 2013-04-20T04:35:40.400 回答