math-suite/Source/TibisMathematicsSuite/KeyboardIO/MyKey.cs

120 lines
3.1 KiB
C#
Raw Normal View History

2018-02-05 23:24:46 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TibisMathematicsSuite.KeyboardIO
{
public class MyKey
{
#region Data types
[Flags]
public enum Modifiers
{
None = 0x0, Alt = 0x1, Ctrl = 0x2, Shift = 0x4, Win = 0x8
}
#endregion
#region Properties
public Modifiers Mods { get; set; }
public System.Windows.Forms.Keys Key { get; set; }
public bool TestModifier(Modifiers m)
{
return ((this.Mods & m) > 0);
}
#endregion
#region Constructors
public MyKey()
{
Mods = Modifiers.None;
Key = System.Windows.Forms.Keys.None;
}
public MyKey(System.Windows.Forms.Keys key)
{
Key = key;
Mods = Modifiers.None;
}
public MyKey(System.Windows.Forms.Keys key, Modifiers mods)
{
Key = key;
Mods = mods;
}
#endregion
#region To and from string
public static MyKey Parse(string str)
{
MyKey key = new MyKey();
System.Windows.Forms.Keys temp;
var keys = str.Split('+');
foreach (var i in keys)
switch (i)
{
case "Alt": key.Mods |= Modifiers.Alt; break;
case "Ctrl": key.Mods |= Modifiers.Ctrl; break;
case "Shift": key.Mods |= Modifiers.Shift; break;
case "Win": key.Mods |= Modifiers.Win; break;
default:
Enum.TryParse<System.Windows.Forms.Keys>(i, out temp);
key.Key = temp;
break;
}
return key;
}
public static string ToString(MyKey key)
{
StringBuilder str = new StringBuilder();
if ((key.Mods & Modifiers.Win) != 0) str.Append("Win+");
if ((key.Mods & Modifiers.Ctrl) != 0) str.Append("Ctrl+");
if ((key.Mods & Modifiers.Alt) != 0) str.Append("Alt+");
if ((key.Mods & Modifiers.Shift) != 0) str.Append("Shift+");
str.Append(Enum.GetName(typeof(System.Windows.Forms.Keys), key.Key));
return str.ToString();
}
public override string ToString()
{
return MyKey.ToString(this);
}
#endregion
#region Overloads
public override bool Equals(object obj)
{
MyKey b = obj as MyKey;
if (b == null) return false;
return (b.Key == this.Key && b.Mods == this.Mods);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator== (MyKey A, MyKey B)
{
if ((object)A == null || (object)B == null) return ((object)A == (object)B);
return (A.Key == B.Key) && (A.Mods == B.Mods);
}
public static bool operator!=(MyKey A, MyKey B)
{
return !(A == B);
}
#endregion
}
}