I have this Winforms code (at the bottom). When I run it, a form appears with "button1". I click the button, it disappears, then I press a key - which should trigger OnKeyDown but nothing happens. I add a breakpoint on MessageBox::Show(...)
line, click a key - now the breakpoint is hit, the MessageBox is displayed and every subsequent key press will also show the MessageBox, even if I remove the breakpoint.
Notes:
- I have tested this on 2 computers running Visual Studio 2013, the project is a .Net 4.5 Winforms project.
- The breakpoint must be set in Visual Studio after starting to debug the project.
- Running the project without debugging never shows the MessageBox
- Per Sriram's note, setting
this.KeyPreview = true
in the constructor causes the MessageBox to always be displayed. Though I still don't understand why setting a breakpoint will cause the MessageBox to be displayed for that debugging session.
public partial class Form1 : Form
{
public Form1()
{
button1 = new Button();
button1.Location = new Point(197, 13);
button1.Name = "button1";
button1.Text = "button1";
button1.Click += button1_Click;
Controls.Add(button1);
Name = "TestForm";
KeyDown += OnKeyDown;
}
private static void OnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
MessageBox.Show("This is shown only after a breakpoint is set on this line");
}
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
}
private readonly Button button1;
}