Reputation: 1176
I have a form that in run time i make many picture box control and i located them on my form. now my question is how can delete a picturebox(in run time) that it is been selected and keybord "delete" is entered. thanks.
Upvotes: 1
Views: 2544
Reputation: 2204
Try This
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Controls.Remove(pictureBox1);
}
if delete on keyboard is selected the picture(has focus).
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Delete)
{
if(pictureBox1.Focus())
{
this.Controls.Remove(pictureBox1);
}
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Regards
Upvotes: 1
Reputation: 5719
You can access the PictureBox
from the controls and use the ControlCollection.Remove
method.
Here is a sample code:
// Remove the PicturBox control if it exists.
private void deleteButton_Click(object sender, System.EventArgs e)
{
if(panel1.Controls.Contains(pictureBox))
{
panel1.Controls.Remove(pictureBox);
}
}
More documentation can be found here
EDIT:
Refer to this link on how to monitor KeyPress
events in C#
Upvotes: 1
Reputation: 176896
try below code in make use of PictureBox.KeyPress : http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.keypress.aspx
PictureBox picture = control as PictureBox;
if (picture != null)
{
this.Controls.Remove(picture);
picture.Dispose();
}
Upvotes: 2