Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Image from PictureBox in C#

how to delete image from picture box when user press "del" key...I dont find any keypress or keydown events for PB.

    private void topRight_pbx_MouseClick(object sender, MouseEventArgs e)
          {
           imgSelected=true;

           //need to accept "delete"key from keyboard?

           topRight_pbx.Image = null;
            topRFile = "";

           }
like image 512
Dark Knight Avatar asked Dec 29 '10 11:12

Dark Knight


4 Answers

Change your imgSelected to something like:

private PictureBox picSelected = null;

On your picturebox click set this variable to the sender:

picSelected = (PictureBox)sender;

Then on the keydown of form or the control that has focus you run the image removal code (Example for form):

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.Delete)
      picSelected.Image = null;
}
like image 52
jpiolho Avatar answered Oct 03 '22 11:10

jpiolho


That's because the PictureBox control can never get the focus, and non-focused controls do not receive keyboard input events.

As the documentation shows, the KeyDown event (and the other events related to keyboard input) are marked with [BrowsableAttribute(false)] because they do not work as expected. They are not intended to be subscribed to by your code.

It's similar to a Label control—you can look at it, but it's not selectable and can't acquire the focus.

You'll need to find another way for the user to indicate that (s)he wants to delete an image currently displayed in a PictureBox control.

like image 31
Cody Gray Avatar answered Oct 03 '22 09:10

Cody Gray


I had a similar problem in one of my projects. I solved it by adding an off-screen textbox. I give focus to the text-box when certain controls get clicked, and use the text-box to handle the keyboard input.

PicureBox SelectedImage=null;

void Image_Click(object sender,...)
{
  SelectedImage=(PictureBox)sender;
  FocusProxy.Focus();
}

void FocusProxy_KeyDown(...)
{
  if(e.KeyData==...)
  {
       SelectedImage.Image=null;
       e.Handled=true;
  }
}
like image 41
CodesInChaos Avatar answered Oct 03 '22 11:10

CodesInChaos


A different way for this could be: If you are drawing on a pictureBox and you want to clear it:

Graphics g = Graphics.FromImage(this.pictureBox1.Image);
g.Clear(this.pictureBox1.BackColor);

After that you can draw again on the control.

I hope this can help to someone

like image 27
Orlando Herrera Avatar answered Oct 03 '22 09:10

Orlando Herrera