Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Shift-Enter event in a textbox

Tags:

c#

wpf

I want a textbox where the user can shift-enter or ctrl-enter to add a newline without submitting. I found the following post on how to do ctrl-enter

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/67ef5912-aaf7-43cc-bfb0-88acdc37f09c

works great! so i added my own block to capture shift enter like so:

  else if (((keyData & swf.Keys.Shift) == swf.Keys.Shift) && ((keyData & swf.Keys.Enter) == swf.Keys.Enter) && Keyboard.FocusedElement == txtMessage)
  {
     // SHIFT ENTER PRESSED!
  }

except now the box is capturing other shift combinations such as the question mark and squiggly braces and then adding a newline. What do I need to change to prevent this from happening?

like image 808
Julien Avatar asked Sep 14 '12 14:09

Julien


3 Answers

I prefeer use keybinnding inputs:

 <TextBox>
      <TextBox.InputBindings>
         <KeyBinding Key="ENTER" Modifiers="Shift" Command="{Binding YoutCommand}"/>
      </TextBox.InputBindings>
 </TextBox>
like image 132
ígor Avatar answered Oct 02 '22 07:10

ígor


I wouldn't mix with WinForms. Try:

<TextBox KeyDown="TextBox_KeyDown" />

with this event handler:

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {
            MessageBox.Show("Control + Enter pressed");
        }
        else if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
        {
            MessageBox.Show("Shift + Enter pressed");
        }
    }
}
like image 30
LPL Avatar answered Oct 02 '22 06:10

LPL


After trying most things i decided to experiment a little my self. And this seems to do the job in an easy

In the designer view. Select the textbox and under the "events" lightningbolt doublecklick on key->KeyDown. you will be placed in the code.

paste this:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Shift)
            {
                if(e.KeyCode == Keys.Enter)
                {
                    MessageBox.Show("shift enter");
                }
            }
        }

If the key shift is pressed. and then in that if-statement. if Enter is pressed a messagebox will pop up.

Swap the messagebox with your task.

like image 38
swedish joe Avatar answered Oct 02 '22 06:10

swedish joe