简体   繁体   中英

How do you detect a square bracket in a KeyDown or KeyUp WPF event?

I'd like to detect if a keystroke would result in a closing square bracket ] in a KeyDown event of a WPF Popup :

private void MyPopup_KeyDown(object sender, KeyEventArgs e)
{
    if (theKeyStrokeWouldResultIsAClosingSquareBracket)
    {
        // ...
        // do stuff
        // ...
        e.Handled = true;
    }
}

The solution has to work for any keyboard layout. Notice that key mappings of different layouts usually differ quite a lot. Therefore checking for the right key combination (like Ctrl + Alt + Digit 9 on a German QWERTZ keyboard or simply OemCloseBrackets on a US QUERTY keyboard) is unfortunately no solution.

How can you accomplish such a detection despite these problems?


EDIT - Adding some information before starting the bounty:

I'm currently implementing an IntelliSense-like function in my current project. The IntelliSense stuff is inspired by this: http://www.codeproject.com/Articles/22803/Intellisense-like-Method-Selection-Pop-up-Window

The custom syntax allows expressions like [abc].[def] > [ghi].[jkl] , where an user should be able to make the intellisense function autocomplete the text in the brackets. To make the intellisense function a bit more similar to Visual Studio's (and lots of other IDEs') behavior, I'd like to enable the user to type a closing square bracket in the popup's list box to force an autocomplete.

您应该使用PreviewTextInput事件 - 这将获取一个TextCompositionEventArgs参数,其Text属性将是PreviewTextInput括号。

您可以向弹出窗口添加一个透明的TextBox ,并订阅它的TextChanged事件而不是Popup上的事件。

If it's a key combination I don't think you'll be able to capture it using a key down event.

if (e.Key == Key.OemCloseBrackets) {

}

is the correct approach for the simple case with an English keyboard. If you would like to cope with the German keyboard that you have described, you should do a string comparison on the text box that you are working with calling from the key up event.

if (txtKeypad.Text.Substring(txtKeypad.Text.Length - 1, 1) == "]")

I hope this helps.

Ed

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