我有一个特殊的TextBox,应该在Enter上验证。
在此验证中,如果已经定义了AcceptButton,则应该提交表格。
在下面的代码中,我有2个textBoxes:一个普通,另一个 - myTextBox - 在Enter上验证自己(DoubleClick表单时间看它):
public partial class Form1 : Form
{
private TextBox TextBox1;
private MyTextBox MyTextBox1;
private Button OKButton;
public Form1()
{
InitializeComponent();
TextBox1 = new TextBox();
TextBox1.Parent = this;
TextBox1.Location = new Point(0, 50);
MyTextBox1 = new MyTextBox();
MyTextBox1.Parent = this;
MyTextBox1.Location = new Point(0, 100);
MyTextBox1.Visible = false;
OKButton = new Button();
OKButton.Parent = this;
OKButton.Location = new Point(0, 125);
OKButton.Click += new EventHandler(OKButton_Click);
this.AcceptButton = OKButton;
}
void OKButton_Click(object sender, EventArgs e)
{
if (MyTextBox1.Visible)
return;
Console.WriteLine("!!! OKButton_Click !!!");
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
MyTextBox1.Visible = true;
base.OnMouseDoubleClick(e);
}
}
public class MyTextBox : TextBox
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
Console.WriteLine("!!! MyTextBox_Validation !!!");
this.Visible = false;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
“Validated”的事实反映在myTextBox可见性上,但这没有用,因为在OKBUtton_Click中,myTextBox1已经变得不可见了......
理想情况下,在myTextBox验证之后,我想在父窗体上停止Enter键消息传播。可能吗?如果没有,我应该如何在不验证表单的情况下验证MyTextBox?
答案 0 :(得分:3)
我希望我能正确理解你的问题。如果处理事件,您是否尝试在ProcessCmdKey覆盖中返回TRUE?返回true告诉事件系统消耗了事件并阻止进一步处理例如:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Enter) {
Console.WriteLine("!!! MyTextBox_Validation !!!");
this.Visible = false;
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}