3

我希望能够使用空格键来修改鼠标按住时的行为。在不知道更好的情况下,我想象它涉及两个(或三个)事件处理程序之间的某种协调 - mousemovekeydownkeyup. 但我想知道是否有某种方法可以完全在一个事件处理程序中处理它 - mousemove.

示例代码让我了解我希望能够做什么......

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (Keyboard.KeyDown == Keys.Space)
                {
                    /* Do modified behavour for left mouse being held down while 
                    space is also held down */
                }
                else
                {
                    // Do normal behavour for left mouse being held down
                }

            }
        }

这样的事情是否可能,或者我是否必须使用 keydown 事件处理程序将空格键的状态保存到类变量并使用鼠标移动处理程序进行检查?

4

4 回答 4

6

IT 可以使用 Control.ModifierKeys 和 Control.MouseButtons 来完成。但仅适用于 shift、ctrl 和 alt 等键。

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {

        if ((Control.ModifierKeys & Keys.Shift) != 0)
        {
            if ((Control.MouseButtons & MouseButtons.Left) != 0)
            { // here you go

            }
        }
    }
于 2012-12-18T20:47:08.620 回答
2

您应该在 KeyDown-Event 中设置一个变量并在 MouseEvent 中检查它:

bool buttonpressed = false;
private void KeyDown_Event(object s, System.Windows.Forms.KeyEventArgs e)
{
   if(e.KeyCode == KeyCode.Space)
      buttonpressed = true;
   else
      buttonpressed = false;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (buttonPressed)
                {
                    /* Do modified behavour for left mouse being held down while 
                    space is also held down */
                }
                else
                {
                    // Do normal behavour for left mouse being held down
                }

            }
        }
于 2012-12-18T20:26:57.087 回答
1

我有一个变量来跟踪何时Keys.Space处于Pressed状态,然后用KeyUpKeyDown事件触发它

 private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
      // Check if Key.Space pressed
      if(SpacePressed) {
           // Do something
      }
 }

 private void KeyPressed_Event(object sender, KeyEventArgs e) {
      // Check if Key.Space pressed
      if(e.Key == Key.Space) {
           SpacePressed = true;
      }
 }

 private void KeyRelease_Event(object sender, KeyEventArgs e) {
      // Check if Key.Space pressed
      if(e.Key == Key.Space) {
           SpacePressed = false;
      }
 }
于 2012-12-18T20:30:15.907 回答
0

您可以使用 PInvoke在 User32.dll中调用GetKeyState 。

于 2012-12-18T21:41:10.060 回答