| Altキー(またはF10キー)でメニューを選択状態にして、Enterキーを押しっぱなしにしてみてください。
メッセージ2が出るとは思いますが、勝手に閉じるのが見えると思います。
メニューをクリックしたときにそのことが表示されているメッセージボックスにも伝わっているのかもしれないですね。
では何が起きているのだろう?
最初に出すメッセージボックス代わりにFormクラスを使ってみました。
Formのイベントをいくつか拾えるようにDebug.WriteLineを入れてみました。
SetVisiableCore(true)は呼ばれているけど、shownイベントが起きていないようですね。
表示しようとするときに何か起きて、そのままクローズ処理が走っているようです。
うーん、なんだろう?
public Form1()
{
Controls.Add(new UserControl1());
Menu = new MainMenu(new MenuItem[] { new MenuItem("&File...", (sender, e) =>
{
var control = Controls[0];
Controls.Remove(control);
control.Dispose();
Controls.Add(new UserControl1());
})});
}
class UserControl1 : UserControl
{
private static bool init = true;
public UserControl1()
{
Controls.Add(new Button());
if (init)
{
init = false;
return;
}
using (var form2 = new Form2())
{
var ret1 = form2.ShowDialog();
var ret2 = MessageBox.Show($"2 ret1={ret1}");
}
}
}
class Form2 : Form
{
public Form2()
{
var btnCancel = new Button();
btnCancel.DialogResult = DialogResult.Cancel;
btnCancel.Location = new Point(10, 10);
btnCancel.Size = new Size(100, 23);
btnCancel.MouseDown += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.btnCancel.mousedown");
btnCancel.Click += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.btnCancel.click");
btnCancel.KeyDown += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.btnCancel.keydown");
btnCancel.KeyPress += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.btnCancel.keypress");
Controls.Add(btnCancel);
CancelButton = btnCancel;
StartPosition = FormStartPosition.CenterScreen;
Size = new Size(500, 400);
Load += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.load");
Shown += (sender, e) => System.Diagnostics.Debug.WriteLine("form2.show");
FormClosing += (sender, e) => System.Diagnostics.Debug.WriteLine($"form2.closing(sender:{sender.GetType().FullName}, reason:{e.CloseReason})");
FormClosed += (sender, e) => System.Diagnostics.Debug.WriteLine($"form2.closed(sender:{sender.GetType().FullName}, reason:{e.CloseReason})");
}
protected override void SetVisibleCore(bool value)
{
System.Diagnostics.Debug.WriteLine($"form2.SetVisibleCore(value:{value})");
base.SetVisibleCore(value);
}
} |