skip to Main Content

I would like to change the text (Content property) of a button when the SHIFT key is pressed. In that cases the button shall execute a different command. That is a common UI behaviour e. g. in Photoshop.

Any idea how to do this.

Many thanks in advance

2

Answers


  1. Chosen as BEST ANSWER

    Here my solution (event is handled at the Window) - many thanks for your input - if there is a better solution kindly comment...

    internal void HandlePreviewKeyDown(KeyEventArgs e)
    {
        IInputElement focusedControl = FocusManager.GetFocusedElement(_window);
        if (( (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) && !(focusedControl?.GetType() == typeof(TextBox)))
        {
           // set button text
            e.Handled = true;
        }
    }
    
    internal void HandlePreviewKeyUp(KeyEventArgs e)
    {
        IInputElement focusedControl = FocusManager.GetFocusedElement(_window);
        if ( (e.Key == Key.LeftShift) || (e.Key == Key.RightShift) && !(focusedControl?.GetType() == typeof(TextBox)))
        {
             // re-set button text
             e.Handled = true;
        }  
    }
    

  2. Add the KeyDown or PreviewKeyDown event to your Button element.

    <Button Width="300" Height="50" Name="btnFunction" KeyDown="btnFunctionKeyDown" Content="Function1"/>
    

    And the C# Code:

    private void btnFunctionKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
        {
            btnFunction.Content = "Function2";
        }
    }
    

    Have a look on this Article for more information:

    https://learn.microsoft.com/de-de/dotnet/api/system.windows.input.keyboard.keydown?view=netcore-3.1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search