如何捕捉Arrow在Panel中的CheckBox的KeyDown事件?

近日,开始做公司Windows Mobile的技术支持给一个项目。在fix bug时遇到一个问题。要求是这样的。
一个Form,嵌入一个Panel,然后再Panel里add 进去几个checkBox控件。然后,当Focus在CheckBox上时,用户会按上下箭头来改变Focus,CheckBox是有一个keydown事件,但是系统不对Arrow这样的事件处理,也就是说,但CLR捕捉到硬件的一个按键后,他把这个按键传给Form,然后,Form再发给Panel,而Panel接受到后直接内化了,就改变了Focus而已,而不发给CheckBox,这样对有如此需求的人来说就很不方便了。
MSDN也对此做了说明:

To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event-handling method to true. Certain keys, such as the TAB, RETURN, ESCAPE, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true.

(MSDN link:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref17/html/E_System_Windows_Forms_Control_KeyDown.htm)



没错,你需要override IsInputKey事件,可是这个时间却在.Net CF2中不支持。此路不通!

那么该如何做呢?
通过P/Invoke调用!

我是向来不喜欢C#的,搞来搞去,很多功能还是需要调用WIN32 API。所以,我们就利用LostFocus或者GetFocus事件发生时,
询问键盘键状态。就可以得到是否用户按了Arrow key了。

 [DllImport("Coredll.dll")]
        private static extern short GetAsyncKeyState(int nVirtKey);
       。。。。
        void CheckBoxLostFocus(object sender, EventArgs e)
        {

            senderText = ((CheckBox)sender).Text;
            if (senderText.Equals(firstChoiceText))
            {
                if (GetAsyncKeyState(0x26) < 0)//press up key
                {
                    ((CheckBox)choiceButtons[choiceTextLength - 1]).Focus();
                }
            }
            if(senderText.Equals(finalChoiceText))
            {
                if(GetAsyncKeyState(0x28)<0)//press down key
                {
                    ((CheckBox)choiceButtons[0]).Focus();
                }
            }
        }
这样就实现了Panel中的CheckBox的KeyDown事件中捕捉Arrow。类似的,你也可以捕捉Tab,Enter键。

你可能感兴趣的:(如何捕捉Arrow在Panel中的CheckBox的KeyDown事件?)