Override ShortCut Keys on .NET RichTextBox
-
06-07-2019 - |
Question
I'm using a RichTextBox (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys.... For example, I don't want Ctrl+I to make the text italic via the RichText method, but to instead run my own method for processing the text.
Any ideas?
Solution
Ctrl + I isn't one of the default shortcuts affected by the ShortcutsEnabled property.
The following code intercepts the Ctrl + I in the KeyDown event so you can do anything you want inside the if block, just make sure to suppress the key press like I've shown.
private void YourRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys & Keys.Control) == Keys.Control && e.KeyCode == Keys.I)
{
// do whatever you want to do here...
e.SuppressKeyPress = true;
}
}
OTHER TIPS
Set the RichtTextBox.ShortcutsEnabled property to true and then handle the shortcuts yourself, using the KeyUp event. E.G.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.ShortcutsEnabled = false;
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
}
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.X)
MessageBox.Show("Overriding ctrl+x");
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow