在鼠标事件期间检查非修改键是否处于按下状态

时间:2014-11-24 06:09:32

标签: c# winforms keyboard mouseevent

根据msdn文档,在WinForms中,我可以检查是否有修改键( SHIFT CTRL ALT )在鼠标事件期间处于按下状态。例如:

private void button1_Click(object sender, System.EventArgs e)
{
   /* If the CTRL key is pressed when the 
    * control is clicked, hide the control. */ 
   if(Control.ModifierKeys == Keys.Control)
   {
     ((Control)sender).Hide();
   }
}

如何在鼠标移动事件期间检查非修改键(例如 Space )是否处于按下状态?

1 个答案:

答案 0 :(得分:-1)

您有几种选择:

选项1 :向您的应用添加自定义消息过滤器:

private KeyMessageFilter _filter = new KeyMessageFilter();

private void Form1_Load(object sender, EventArgs e)
{
    Application.AddMessageFilter(_filter);    
}    

public class KeyMessageFilter : IMessageFilter
{
    private Dictionary<Keys, bool> _keyTable = new Dictionary<Keys, bool>();

    public Dictionary<Keys, bool> KeyTable
    {
        get { return _keyTable; }
        private set { _keyTable = value; }
    }

    public bool IsKeyPressed()
    {
        return _keyPressed; 
    }

    public bool IsKeyPressed(Keys k)
    {
        bool pressed = false;

        if (KeyTable.TryGetValue(k, out pressed))
        {
            return pressed;                  
        }

        return false; 
    }

    private const int WM_KEYDOWN = 0x0100;

    private const int WM_KEYUP = 0x0101;

    private bool _keyPressed = false;


    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            KeyTable[(Keys)m.WParam] = true;

            _keyPressed = true;
        }

        if (m.Msg == WM_KEYUP)
        {                
            KeyTable[(Keys)m.WParam] = false;

            _keyPressed = false;
        }

        return false;        
}

选项2 :使用之前链接的GetKeyState API函数:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace MouseKeyboardStateTest
{
  public abstract class Keyboard
  {
    [Flags]
    private enum KeyStates
    {
      None = 0,
      Down = 1,
      Toggled = 2
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern short GetKeyState(int keyCode);

    private static KeyStates GetKeyState(Keys key)
    {
      KeyStates state = KeyStates.None;

      short retVal = GetKeyState((int)key);

      //If the high-order bit is 1, the key is down
      //otherwise, it is up.
      if ((retVal & 0x8000) == 0x8000)
        state |= KeyStates.Down;

      //If the low-order bit is 1, the key is toggled.
      if ((retVal & 1) == 1)
        state |= KeyStates.Toggled;

      return state;
    }

    public static bool IsKeyDown(Keys key)
    { 
      return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
    }

    public static bool IsKeyToggled(Keys key)
    { 
      return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
    }
  }
}

选项3: 自己处理KeyDown和KeyUp事件。这不是最好的方法,但对于小型应用来说会很好。