简体   繁体   中英

How do I create keyboard input in a wpf application?

I want to make a wpf application in c# that displays some text on screen, and where the user is supposed to write a response and press enter to submit the response. I don't want to use a textbox, since there is only one line for the text input in the window, and I don't want the user to have to click to select the textbox. I want the application to be mouse-free.

My question is: How do I make it so that when the user has written their answer, they can submit the response simply by pressing enter?

I have tried the following snippet of code which I found on a microsoft help website:

private void OnKeyDownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {

            doSomething();
        }
    }

I suppose I have to add some code elsewhere, but I'm not sure where or what I need to add.

If you have a button that you're using for submit, you can easily set it as the default by using the IsDefault=true (wrote a tip about doing this and the cancel for the escape here .)

Other than that, you'll have to have somewhere to write it (yet you don't want a textbox? you can select it by default, or tab into it if you don't have the focus there), and you can handle the keydown to "catch" the Enter otherwise.

If you want to make sure your window process every Enter key press without care what control is focused you can use PreviewKeyDown event:

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        //Process user input
        e.Handled = true;
    }
} 

Of course if you are doing mvvm you can create a behavior to encapsulate the event handler:

 public class WindowBehavior : Behavior<Window>
    {
        protected override void OnAttached()
        {
            AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
        }

    private void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            MessageBox.Show("Enter from Window");
            e.Handled = true;
        }
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
    }

I suggest you to read this article about bubble, tunneling and direct events basic for WPF events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM