Example #1
0
 protected static string SerializeKey(Key key)
 {
   if (key.IsPrintableKey)
     return "P:" + key.RawCode;
   else if (key.IsSpecialKey)
     return "S:" + key.Name;
   else
     throw new NotImplementedException(string.Format("Cannot serialize key '{0}', it is neither a printable nor a special key", key));
 }
Example #2
0
 public override void OnKeyPreview(ref Key key)
 {
   base.OnKeyPreview(ref key);
   if (!HasFocus)
     return;
   // We handle "normal" button presses in the KeyPreview event, because the "Default" event needs
   // to be handled after the focused button was able to consume the event
   if (key == Key.None) return;
   if (key == Key.Ok)
   {
     Execute();
     key = Key.None;
   }
 }
Example #3
0
 protected void RegisterKeyBinding()
 {
   if (_registeredScreen != null)
     return;
   if (Key == null)
     return;
   Screen screen = Screen;
   if (screen == null)
     return;
   _registeredScreen = screen;
   _registeredKey = Key;
   _registeredScreen.AddKeyBinding(_registeredKey, new KeyActionDlgt(Execute));
 }
 protected void AvoidDuplicateKeys(Key key)
 {
   if (_workflowActionShortcuts.ContainsKey(key))
     throw new ArgumentException(string.Format("A global shortcut for Key '{0}' was already registered with action '{1}'", key, _workflowActionShortcuts[key].Name));
   if (_workflowStateShortcuts.ContainsKey(key))
     throw new ArgumentException(string.Format("A global shortcut for Key '{0}' was already registered with state '{1}'", key, _workflowStateShortcuts[key].Name));
 }
Example #5
0
    public static bool ConvertType(object value, Type targetType, out object result)
    {
      result = value;
      if (value == null)
        return true;
      if (value is string && targetType == typeof(Type))
      {
        string typeName = (string)value;
        Type type;
        if (!_objectClassRegistrations.TryGetValue(typeName, out type))
          type = Type.GetType(typeName);
        if (type != null)
        {
          result = type;
          return true;
        }
      }
      // Don't convert LateBoundValue (or superclass ValueWrapper) here... instances of
      // LateBoundValue must stay unchanged until some code part explicitly converts them!
      if (value is ResourceWrapper)
      {
        object resource = ((ResourceWrapper)value).Resource;
        if (TypeConverter.Convert(resource, targetType, out result))
        {
          if (ReferenceEquals(resource, result))
          {
            // Resource must be copied because setters and other controls most probably need a copy of the resource.
            // If we don't copy it, Setter is not able to check if we already return a copy because our input value differs
            // from the output value, even if we didn't do a copy here.
            result = MpfCopyManager.DeepCopyCutLVPs(result);
          }
          return true;
        }
      }
      if (value is string && targetType == typeof(FrameworkElement))
      {
        // It doesn't suffice to have an implicit data template declaration which returns a label for a string.
        // If you try to build a ResourceWrapper with a string and assign that ResourceWrapper to a Button's Content property
        // with a StaticResource, for example, the ResourceWrapper will be assigned directly without the data template being
        // applied. To make it sill work, we need this explicit type conversion here.
        result = new Label { Content = (string)value, Color = Color.White };
        return true;
      }
      if (targetType == typeof(Transform))
      {
        string v = value.ToString();
        string[] parts = v.Split(new[] { ',' });
        if (parts.Length == 6)
        {
          float[] f = new float[parts.Length];
          for (int i = 0; i < parts.Length; ++i)
          {
            object obj;
            TypeConverter.Convert(parts[i], typeof(double), out obj);
            f[i] = (float)obj;
          }
          System.Drawing.Drawing2D.Matrix matrix2D = new System.Drawing.Drawing2D.Matrix(f[0], f[1], f[2], f[3], f[4], f[5]);
          Static2dMatrix matrix = new Static2dMatrix();
          matrix.Set2DMatrix(matrix2D);
          result = matrix;
          return true;
        }
      }
      else if (targetType == typeof(Vector2))
      {
        result = Convert2Vector2(value.ToString());
        return true;
      }
      else if (targetType == typeof(Vector3))
      {
        result = Convert2Vector3(value.ToString());
        return true;
      }
      else if (targetType == typeof(Vector4))
      {
        result = Convert2Vector4(value.ToString());
        return true;
      }
      else if (targetType == typeof(Thickness))
      {
        Thickness t;
        float[] numberList = ParseFloatList(value.ToString());

        if (numberList.Length == 1)
        {
          t = new Thickness(numberList[0]);
        }
        else if (numberList.Length == 2)
        {
          t = new Thickness(numberList[0], numberList[1]);
        }
        else if (numberList.Length == 4)
        {
          t = new Thickness(numberList[0], numberList[1], numberList[2], numberList[3]);
        }
        else
        {
          throw new ArgumentException("Invalid # of parameters");
        }
        result = t;
        return true;
      }
      else if (targetType == typeof(Color))
      {
        Color color;
        if (ColorConverter.ConvertColor(value, out color))
        {
          result = color;
          return true;
        }
      }
      else if (targetType == typeof(Brush) && value is string || value is Color)
      {
        try
        {
          Color color;
          if (ColorConverter.ConvertColor(value, out color))
          {
            SolidColorBrush b = new SolidColorBrush
            {
              Color = color
            };
            result = b;
            return true;
          }
        }
        catch (Exception)
        {
          return false;
        }
      }
      else if (targetType == typeof(GridLength))
      {
        string text = value.ToString();
        if (text == "Auto")
          result = new GridLength(GridUnitType.Auto, 0.0);
        else if (text == "AutoStretch")
          result = new GridLength(GridUnitType.AutoStretch, 1.0);
        else if (text.IndexOf('*') >= 0)
        {
          int pos = text.IndexOf('*');
          text = text.Substring(0, pos);
          if (text.Length > 0)
          {
            object obj;
            TypeConverter.Convert(text, typeof(double), out obj);
            result = new GridLength(GridUnitType.Star, (double)obj);
          }
          else
            result = new GridLength(GridUnitType.Star, 1.0);
        }
        else
        {
          double v = double.Parse(text);
          result = new GridLength(GridUnitType.Pixel, v);
        }
        return true;
      }
      else if (targetType == typeof(string) && value is IResourceString)
      {
        result = ((IResourceString)value).Evaluate();
        return true;
      }
      else if (targetType.IsAssignableFrom(typeof(IExecutableCommand)) && value is ICommand)
      {
        result = new CommandBridge((ICommand)value);
        return true;
      }
      else if (targetType == typeof(Key) && value is string)
      {
        string str = (string)value;
        // Try a special key
        result = Key.GetSpecialKeyByName(str);
        if (result == null)
          if (str.Length != 1)
            throw new ArgumentException(string.Format("Cannot convert '{0}' to type Key", str));
          else
            result = new Key(str[0]);
        return true;
      }
      else if (targetType == typeof(string) && value is IEnumerable)
      {
        result = StringUtils.Join(", ", (IEnumerable)value);
        return true;
      }
      result = value;
      return false;
    }
Example #6
0
 protected void HandleClipboardKeys(ref Key key)
 {
   if (!HasFocus)
     return;
   if (key == Key.Cut)
   {
     if (ServiceRegistration.Get<IClipboardManager>().SetClipboardText(Text))
     {
       Text = string.Empty;
       key = Key.None;
     }
   }
   else if (key == Key.Copy)
   {
     if (ServiceRegistration.Get<IClipboardManager>().SetClipboardText(Text))
       key = Key.None;
   }
   else if (key == Key.Paste)
   {
     string text;
     if (ServiceRegistration.Get<IClipboardManager>().GetClipboardText(out text))
     {
       // If caret is placed on end, simply append the text
       if (CaretIndex == Text.Length)
         Text += text;
       else
       {
         string beforeCaret = Text.Substring(0, CaretIndex);
         string afterCaret = Text.Substring(CaretIndex);
         Text = string.Format("{0}{1}{2}", beforeCaret, text, afterCaret);
         CaretIndex = beforeCaret.Length + text.Length;
       }
       key = Key.None;
     }
   }
 }
Example #7
0
 /// <summary>
 /// Will be called when a key is pressed. Derived classes may override this method
 /// to implement special key handling code.
 /// </summary>
 /// <param name="key">The key. Should be set to 'Key.None' if handled by child.</param> 
 public virtual void OnKeyPressed(ref Key key)
 {
   foreach (UIElement child in GetChildren())
   {
     if (!child.IsVisible) continue;
     child.OnKeyPressed(ref key);
     if (key == Key.None) return;
   }
 }
Example #8
0
 public MappedKeyCode(Key key, string code)
 {
   _key  = key;
   _code = code;
 }
Example #9
0
 /// <summary>
 /// Serializes a <see cref="Key"/> into a string. This method supports both printable and special keys.
 /// </summary>
 /// <param name="key">Key</param>
 /// <returns>Key string.</returns>
 /// <exception cref="ArgumentException">If key is neither printable nor special key.</exception>
 public static string SerializeKey(Key key)
 {
   if (key.IsPrintableKey)
     return "P:" + key.RawCode;
   if (key.IsSpecialKey)
     return "S:" + key.Name;
   throw new ArgumentException(string.Format("Cannot serialize key '{0}', it is neither a printable nor a special key", key));
 }
Example #10
0
 /// <summary>
 /// Creates a new instance of <see cref="KeyboardEventArgs"/>.
 /// </summary>
 /// <param name="timestamp">Time when the input occurred.</param>
 /// <param name="key">Key to associate with this event.</param>
 public KeyEventArgs( /*KeyboardDevice keyboard,*/ int timestamp, Key key)
   : base( /*keyboard,*/ timestamp)
 {
   _key = key;
 }
 public abstract void HandleInput(ref Key key);
Example #12
0
 public MappedKeyCode(Key key, int code)
 {
   Key  = key;
   Code = code;
 }
 public override void OnKeyPressed(ref Key key)
 {
   base.OnKeyPressed(ref key);
   if (!IsActive || key == Key.None)
     return;
   ICommandStencil command = KeyPressedCommand;
   if (command == null)
     return;
   command.Execute(new object[] {key});
 }
Example #14
0
    public override void OnKeyPressed(ref Key key)
    {
      base.OnKeyPressed(ref key);

      if (key == Key.None)
        // Key event was handeled by child
        return;
      int updatedStartsWithIndex = -1;
      try
      {
        if (!CheckFocusInScope())
          return;

        if (key.IsPrintableKey)
        {
          if (_startsWithIndex == -1 || _startsWith != key.RawCode)
          {
            _startsWith = key.RawCode.Value;
            updatedStartsWithIndex = 0;
          }
          else
            updatedStartsWithIndex = _startsWithIndex + 1;
          key = Key.None;
          if (!FocusItemWhichStartsWith(_startsWith, updatedStartsWithIndex))
            updatedStartsWithIndex = -1;
        }
      }
      finally
      {
        // Will reset the startsWith function if no char was pressed
        _startsWithIndex = updatedStartsWithIndex;
      }
    }
Example #15
0
 public override void OnKeyPressed(ref Key key)
 {
   // We handle the "Default" event here, "normal" events will be handled in the KeyPreview event
   base.OnKeyPressed(ref key);
   if (key == Key.None) return;
   if (IsDefault && key == Key.Ok)
   {
     Execute();
     key = Key.None;
   }
 }
Example #16
0
 internal override void OnKeyPreview(ref Key key)
 {
   base.OnKeyPreview(ref key);
   if (!HasFocus)
     return;
   if (key == Key.None) return;
   IExecutableCommand cmd = ContextMenuCommand;
   if (key == Key.ContextMenu && ContextMenuCommand != null)
   {
     if (cmd != null)
       InputManager.Instance.ExecuteCommand(cmd.Execute);
     key = Key.None;
   }
 }
 protected void AddKeyBinding_NeedLock(Key key, VoidKeyActionDlgt action)
 {
   _registeredKeyBindings.Add(key);
   IInputManager inputManager = ServiceRegistration.Get<IInputManager>();
   inputManager.AddKeyBinding(key, action);
 }
Example #18
0
    public void OnKeyPress(Key key)
    {
      if (_bdReader == null || !IsHandlingUserInput)
        return;

      BluRayAPI.BDKeys translatedKey;
      if (BluRayAPI.KeyMapping.TryGetValue(key, out translatedKey))
      {
        BluRayPlayerBuilder.LogDebug("BDPlayer: Key Press {0} -> {1}", key, translatedKey);
        _bdReader.Action((int)translatedKey);
      }
    }
Example #19
0
 public KeyAction(Key key, KeyActionDlgt action)
 {
   _key = key;
   _action = action;
 }
Example #20
0
 public void KeyPress(Key key)
 {
   _lastInputTime = DateTime.Now;
   TryEvent_NoLock(new KeyEvent(key));
 }
Example #21
0
 public override void OnKeyPreview(ref Key key)
 {
   // Clipboard handling is independent from actual input handler
   HandleClipboardKeys(ref key);
   AbstractTextInputHandler textInputHandler = _textInputHandler;
   if (textInputHandler != null && IsEnabled)
     textInputHandler.HandleInput(ref key);
   base.OnKeyPreview(ref key);
 }
Example #22
0
 public void AddKeyBinding(Key key, KeyActionDlgt action)
 {
   lock (_syncObj)
     _keyBindings[key] = new KeyAction(key, action);
 }
Example #23
0
 public override void OnKeyPressed(ref Key key)
 {
   base.OnKeyPressed(ref key);
   if (HasFocus && key == Key.Ok)
   {
     key = Key.None;
     Screen screen = Screen;
     if (screen != null)
       screen.ShowVirtualKeyboard(_textProperty, new VirtualKeyboardSettings
         {
           ElementArrangeBounds = ActualBounds,
           TextStyle = IsPassword ? VirtualKeyboardTextStyle.PasswordText : VirtualKeyboardTextStyle.None
         });
   }
 }
Example #24
0
 public void AddKeyBinding(Key key, VoidKeyActionDlgt action)
 {
   AddKeyBinding(key, () =>
       {
         action();
         return true;
       });
 }
 public override void OnKeyPressed(ref Key key)
 {
   base.OnKeyPressed(ref key);
   FrameworkElement templateControl = TemplateControl;
   if (IsVisible && key == Key.Ok && templateControl != null && !templateControl.IsMouseOver)
     Close();
 }
Example #26
0
 public void RemoveKeyBinding(Key key)
 {
   lock (_syncObj)
     _keyBindings.Remove(key);
 }
Example #27
0
    public override void OnKeyPressed(ref Key key)
    {
      base.OnKeyPressed(ref key);

      if (key == Key.None)
        // Key event was handeled by child
        return;

      if (!CheckFocusInScope())
        return;

      if (key == Key.Down && OnDown())
        key = Key.None;
      else if (key == Key.Up && OnUp())
        key = Key.None;
      else if (key == Key.Left && OnLeft())
        key = Key.None;
      else if (key == Key.Right && OnRight())
        key = Key.None;
      else if (key == Key.Home && OnHome())
        key = Key.None;
      else if (key == Key.End && OnEnd())
        key = Key.None;
      else if (key == Key.PageDown && OnPageDown())
        key = Key.None;
      else if (key == Key.PageUp && OnPageUp())
        key = Key.None;
    }
Example #28
0
 public KeyEvent(Key key)
 {
   _key = key;
 }
Example #29
0
 protected void UnregisterKeyBinding()
 {
   if (_registeredScreen != null && _registeredKey != null)
     _registeredScreen.RemoveKeyBinding(_registeredKey);
   _registeredScreen = null;
   _registeredKey = null;
 }
Example #30
0
    internal override void OnKeyPreview(ref Key key)
    {
      bool checkedChanged = false;
      if (HasFocus && key == Key.Ok)
      {
        checkedChanged = true;
        IsChecked = !IsChecked; // First toggle the state, then execute the base handler
      }

      base.OnKeyPreview(ref key);
      if (checkedChanged)
      {
        key = Key.None;
        if (IsChecked)
        {
          IExecutableCommand cmd = Checked;
          if (cmd != null)
            InputManager.Instance.ExecuteCommand(cmd.Execute);
        }
        else
        {
          IExecutableCommand cmd = Unchecked;
          if (cmd != null)
            InputManager.Instance.ExecuteCommand(cmd.Execute);
        }
      }
    }