- - Command Management, () .
WPF , .
, .
KeyStore. , .
public delegate void KeyStoreEventHandler(string name);
class KeyStore : IMessageFilter
{
[DllImport("user32.dll")]
static extern short GetKeyState(Keys key);
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private static KeyStore s_instance = null;
private bool _shift = false;
private bool _control = false;
private Dictionary<Keys, string> _definitions;
public event KeyStoreEventHandler KeyPress;
public void AddKeyDefinition(string name, Keys key, Keys modifiers)
{
Keys combined = key | modifiers;
_definitions[combined] = name;
}
public bool PreFilterMessage(ref Message m)
{
bool handled = false;
Keys key = Keys.None;
switch (m.Msg)
{
case WM_KEYUP:
key = (Keys)m.WParam;
handled = HandleModifier(key, false);
break;
case WM_KEYDOWN:
key = (Keys)m.WParam;
handled = HandleModifier(key, true);
if (false == handled)
{
handled = HandleDefinedKey(key);
}
break;
}
return handled;
}
private bool HandleDefinedKey(Keys key)
{
bool handled = false;
Keys combined = key;
if (_shift) combined |= Keys.Shift;
if (_control) combined |= Keys.Control;
string name = null;
if (true == _definitions.TryGetValue(combined, out name))
{
OnKeyPress(name);
handled = true;
}
return handled;
}
private bool HandleModifier(Keys key, bool isDown)
{
bool handled = false;
switch (key)
{
case Keys.RControlKey:
case Keys.ControlKey:
_control = isDown;
handled = true;
break;
case Keys.RShiftKey:
case Keys.ShiftKey:
_shift = isDown;
handled = true;
break;
}
return handled;
}
private void OnKeyPress(string name)
{
if (null != KeyPress) KeyPress(name);
_control =
-127 == GetKeyState(Keys.ControlKey) ||
-127 == GetKeyState(Keys.RControlKey);
_shift =
-127 == GetKeyState(Keys.ShiftKey) ||
-127 == GetKeyState(Keys.RShiftKey);
}
public static KeyStore Instance
{
get
{
if (null == s_instance)
s_instance = new KeyStore();
return s_instance;
}
}
private KeyStore()
{
_definitions = new Dictionary<Keys, string>();
}
}
, Application. Main() (, Program.cs) Application.Run():
Application.AddMessageFilter(KeyStore.Instance);
, Application.Run(). KeyStore .
KeyStore , , Form_Load :
KeyStore.Instance.AddKeyDefinition("CloseApp", Keys.F12, Keys.None);
KeyStore.Instance.AddKeyDefinition("Save", Keys.S, Keys.Control);
: F12 Control + S.
, CloseApp Save.
KeyStore.Instance.KeyPress += new KeyStoreEventHandler(KeyStore_KeyPress);
MessageBox.Show(), , :
void KeyStore_KeyPress(string name)
{
MessageBox.Show(String.Format("Key '{0}' was pressed!", name));
}
, , , . .
KeyStore , . Main(), Application.Run() .