At long last I found the answer in another question: the OnKeyDown
method of a text control gets called before the KeyDown
event is fired, so rather than listening to the KeyDown
event, you must create a subclass of RichEditBox
and override the OnKeyDown
method. Then in your XAML markup or wherever you're instantiating the RichEditBox
, use your custom subclass instead. As a somewhat-related example, I created an override of TextBox
that prevents undo and redo operations:
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BetterTextBox sealed : public Windows::UI::Xaml::Controls::TextBox
{
public:
BetterTextBox() {}
virtual ~BetterTextBox() {}
virtual void OnKeyDown(Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e) override
{
Windows::System::VirtualKey key = e->Key;
Windows::UI::Core::CoreVirtualKeyStates ctrlState = Windows::UI::Core::CoreWindow::GetForCurrentThread()->GetKeyState(Windows::System::VirtualKey::Control);
if ((key == Windows::System::VirtualKey::Z || key == Windows::System::VirtualKey::Y) &&
ctrlState != Windows::UI::Core::CoreVirtualKeyStates::None)
{
e->Handled = true;
}
// only call the base implementation if we haven't already handled the input
if (!e->Handled)
{
Windows::UI::Xaml::Controls::TextBox::OnKeyDown(e);
}
}
};