只要你可以要求
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;
}
}