I have a cancel button on my form. I want to determine inside the WndProc
method that this Cancel
button is clicked and write some code for it. This is absolutely necessary because otherwise I'm not able to cancel all other control validation events that are yet to be performed.
Please help.
.NET - 2.0, WinForms
This is how you could parse the WndProc message for a left-click on a child control:
protected override void WndProc(ref Message m)
{
// http://msdn.microsoft.com/en-us/library/windows/desktop/hh454920(v=vs.85).aspx
// 0x210 is WM_PARENTNOTIFY
// 513 is WM_LBUTTONCLICK
if (m.Msg == 0x210 && m.WParam.ToInt32() == 513)
{
var x = (int)(m.LParam.ToInt32() & 0xFFFF);
var y = (int)(m.LParam.ToInt32() >> 16);
var childControl = this.GetChildAtPoint(new Point(x, y));
if (childControl == cancelButton)
{
// ...
}
}
base.WndProc(ref m);
}
BTW: this is 32-bit code.
And if there are controls which failed validation then CauseValidation does not help
Well, sure it does, that's what the property was designed to do. Here's an example form to show this at work. Drop a textbox and a button on the form. Note how you can click the button to clear the textbox, even though the box always fails its validation. And how you can close the form.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
textBox1.Validating += new CancelEventHandler(textBox1_Validating);
button1.Click += new EventHandler(button1_Click);
button1.CausesValidation = false;
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
private void textBox1_Validating(object sender, CancelEventArgs e) {
// Always fail validation
e.Cancel = true;
}
void button1_Click(object sender, EventArgs e) {
// Your Cancel button
textBox1.Text = string.Empty;
}
void Form1_FormClosing(object sender, FormClosingEventArgs e) {
// Allow the form to close even though validation failed
e.Cancel = false;
}
}