I am trying to disable people from deleting a textbox in a richtextbox. The project is using windows form.
Here is the code I have:
private void
My solution:
void richTextBox1_TextChanged(object sender, EventArgs e) {
richTextBox1.SelectAll();
richTextBox1.SelectionProtected = true;
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
Side note: yes, this will flicker. Proof of concept only. To avoid the flicker, see How to append text to RichTextBox without scrolling and losing selection?
My solution is some kind of the combination of SerkanOzvatan's and LarsTech's answers. Here is the code:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
e.Handled = true;
MessageBox.Show("Try not to delete... write freely and openly");
// Does not show message box...
}
}
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
richTextBox1.SelectionProtected = richTextBox1.SelectionLength > 0;
}
It works great :)
And here is another solution of my own which also works great, especially if you want to do with a TextBox
(not a RichTextBox
), it doesn't have a SelectionProtected
, and this is used OK for both TextBox
and RichTextBox
(just change the class name in the following code accordingly):
public class WritableRichTextBox : RichTextBox
{
protected override bool ProcessKeyMessage(ref Message m)
{
int virtualKey = m.WParam.ToInt32();
if (SelectionLength > 0 || virtualKey == 0x08 || virtualKey == 0x2e)
{
if (virtualKey != 0x25 && virtualKey != 0x26 && virtualKey != 0x27 && virtualKey != 0x28)
return true;
}
return base.ProcessKeyMessage(ref m);
}
}
You must add Back key to prevent delete :
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
e.Handled = true;
MessageBox.Show("Delete Pressed");
// Does not show message box...
}
}
Edit:
Non-selectable RichTextBox :
public class ViewOnlyRichTextBox : System.Windows.Forms.RichTextBox {
// constants for the message sending
const int WM_SETFOCUS = 0x0007;
const int WM_KILLFOCUS = 0x0008;
protected override void WndProc(ref Message m) {
if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;
base.WndProc (ref m);
}
}
Per the MSDN documentation on KeyPressEventArgs.KeyChar, you cannot get or set the DELETE key using that event. You will need to use the KeyEventArgs.KeyCode instead, subscribing to the KeyDown
and KeyUp
events.
Instead Of KeyPress event use KeyDown In RichText Box.
try this to prevent from deleting text in RichText Box
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 46)
e.Handled = true;
}
If you want to disallow both delete and backspace You Can Change KeyDown Event as follows
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 8 || e.KeyValue == 46)
e.Handled = true;
}