How to trap Delete keypress?

G

Guest

In my WinForms app I wanted to implement a Read-Only textbox. I didn't like
the appearance a textbox takes on when the ReadOnly property is set true so
instead I trapped the KeyPress event with a generic event handler:

private void textBoxMakeReadOnly(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}


I *thought* this was working perfectly until I selected some characters and
pressed 'Delete'. It didn't trap the Delete key! I even tried monitoring
the KeyDown event but no luck there either.

So how does one trap the pressing of the Delete key?
 
B

Barry Kelly

Robert W. said:
In my WinForms app I wanted to implement a Read-Only textbox. I didn't like
the appearance a textbox takes on when the ReadOnly property is set true

By default, it changes the background color to SystemColors.ButtonFace.
You can still change the BackColor property to a different color. If you
set it to SystemColors.Window, then the color will be the same as an
enabled text control.

Be careful what you implement, though - if a cursor is visible and the
background color is SystemColors.Window, users will be surprised to find
that the text is read-only.
I *thought* this was working perfectly until I selected some characters and
pressed 'Delete'. It didn't trap the Delete key! I even tried monitoring
the KeyDown event but no luck there either.

If you handle the KeyDown event as well, it will block the Delete key:

---8<---
using System;
using System.Windows.Forms;
using System.Drawing;

class App
{
static void Main()
{
Form form = new Form();
TextBox box = new TextBox();
box.Location = new Point(10, 10);
box.Size = new Size(100, 20);
box.KeyPress += delegate(object sender, KeyPressEventArgs e)
{
e.Handled = true;
};
box.KeyDown += delegate(object sender, KeyEventArgs e)
{
e.Handled = true;
};
box.Parent = form;
box.Text = "This is test text";
Application.Run(form);
}
}
--->8---

The text control shown by this program will block both new character
input and special keys like delete and arrow keys. In fact, it even
blocks key combinations like Alt+F4.

-- Barry
 
J

JasonS

So how does one trap the pressing of the Delete key?

As Barry says, don't confuse users, just change the background in a
different way if you want it to be a standard within your app.
You should ideally create your own control too so you can globally change
it if you feel the need later.

e.g.
class ReadonlyTextbox : System.Windows.Forms.TextBox
{
public ReadonlyTextbox()
{
this.ReadOnly = true;
this.BackColor = System.Drawing.Color.Yellow;
}
}

Cheers,
Jason
 
G

Guest

Barry, Jason:

Thank you! I feel stupid because I never realized all this before. Thanks
for clearing it up for me!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top