How do I capture Ctrl + Enter key press in my TextBox?

Platform: WPF| Category: Input and Commands.

You can do so by listening to the ComponentDispatcher.ThreadPreprocessMessage in your window as follows:

[C#]
using System;
using System.Windows;
using System.Windows.Controls;
using swf = System.Windows.Forms;
using System.Windows.Interop;
using System.Windows.Forms.Integration;
using System.Windows.Input;

namespace WpfTestHarness
{
    public partial class CustomShortcutHandlingDemo : Window
    {
        public CustomShortcutHandlingDemo()
        {
            InitializeComponent();

            // Registering against a stack event will cause memory leak, please unregister this event when you are done with it.
            ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;
        }

        const int WM_KEYDOWN = 0x100;
        const int WM_SYSKEYDOWN = 0x0104;
        private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN)
            {
                // Examine if the Control and Enter keys are pressed, we also need to make sure that the
                // currently keyborad focused element is TextBox instance itself.
                swf.Keys keyData = ((swf.Keys)((int)((long)msg.wParam))) | swf.Control.ModifierKeys;
                if (((keyData & swf.Keys.Control) == swf.Keys.Control) &&
                    ((keyData & swf.Keys.Enter) == swf.Keys.Enter) &&
                    Keyboard.FocusedElement == textBox)
                {
                    MessageBox.Show('Ctrl+Enter is pressed');
                }
            }
        }
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.