代码之家  ›  专栏  ›  技术社区  ›  saihenjin

Visual C++监视键序列

  •  1
  • saihenjin  · 技术社区  · 11 年前

    如果我在C++中有一些表单应用程序,我将如何设置一些东西,以便它监视特定的键序列来执行一些操作?比如,看着用户按特定顺序点击箭头键,当它发生时打开另一个窗体?

    (很可能这是.net?我刚开始做表格,所以我在这里有点迷路了。)

    1 回复  |  直到 11 年前
        1
  •  0
  •   jerry    11 年前

    只要你可以要求 Form 有焦点,一个简单的版本包括设置 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;
        }
    }