C# and Arrow Keys

前端 未结 2 1260
暗喜
暗喜 2021-02-03 23:35

I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys.

<
2条回答
  •  无人共我
    2021-02-04 00:16

    I upvoted Tokabi's answer, but for comparing keys there is some additional advice on StackOverflow.com here. Here are some functions which I used to help simplify everything.

       public Keys UnmodifiedKey(Keys key)
        {
            return key & Keys.KeyCode;
        }
    
        public bool KeyPressed(Keys key, Keys test)
        {
            return UnmodifiedKey(key) == test;
        }
    
        public bool ModifierKeyPressed(Keys key, Keys test)
        {
            return (key & test) == test;
        }
    
        public bool ControlPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Control);
        }
    
        public bool AltPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Alt);
        }
    
        public bool ShiftPressed(Keys key)
        {
            return ModifierKeyPressed(key, Keys.Shift);
        }
    
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (KeyPressed(keyData, Keys.Left) && AltPressed(keyData))
            {
                int n = code.Text.IndexOfPrev('<', code.SelectionStart);
                if (n < 0) return false;
                if (ShiftPressed(keyData))
                {
                    code.ExpandSelectionLeftTo(n);
                }
                else
                {
                    code.SelectionStart = n;
                    code.SelectionLength = 0;
                }
                return true;
            }
            else if (KeyPressed(keyData, Keys.Right) && AltPressed(keyData))
            {
                if (ShiftPressed(keyData))
                {
                    int n = code.Text.IndexOf('>', code.SelectionEnd() + 1);
                    if (n < 0) return false;
                    code.ExpandSelectionRightTo(n + 1);
                }
                else
                {
                    int n = code.Text.IndexOf('<', code.SelectionStart + 1);
                    if (n < 0) return false;
                    code.SelectionStart = n;
                    code.SelectionLength = 0;
                }
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    

提交回复
热议问题