开发者

Delete Image from PictureBox in C#

how to delete image from picture box when user press "del" key...I dont f开发者_如何转开发ind 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 = "";

           }


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;
}


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.


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;
  }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜