我有一个用户控件,它是一个标签和一个文本框。此控件将以表单形式动态创建。我想使用删除键按下删除此控件.Click事件用于关注用于触发keydown事件的控件和按键方法。这是我的代码
private void usereditFieldControl_Click(object sender, EventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
editFieldControl.KeyDown += new KeyEventHandler(Key_pressed);
}
private void Key_pressed(object sender, KeyEventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
if (e.KeyCode == Keys.Delete)
{
editFieldControl.Dispose();
}
}
答案 0 :(得分:0)
您可以使用以下代码。 “sender”可以转换为更通用的“Control”类:
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Delete) {
Control ctl = (Control)sender;
ctl.Dispose();
this.Controls.Remove(ctl);
}
}
如果您的控件是在运行时以动态方式创建的,请不要忘记向KeyDown事件添加处理程序,如下所示:
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
答案 1 :(得分:0)
private void usereditFieldControl_Click(object sender, EventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
editFieldControl.KeyDown += new KeyEventHandler(Key_pressed);
}
private void Key_pressed(object sender, KeyEventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
if (e.KeyCode == Keys.Delete)
{
//Find control
for (int i = 0; i < editFieldControl.Parent.Controls.Count(); i++) {
if (editFieldControl.Parent.Controls[i].Name == editFieldControl.Name) {
//Unhook events to prevent memory leaks
editFieldControl.KeyDown -= new KeyEventHandler(Key_pressed);
//Remove control from collection
editFieldControl.Parent.Controls.RemoveAt[i];
break;
}
}
//repaint
this.Invalidate();
}
}
未经测试,写在iPhone上